main.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. """
  2. 主程序入口
  3. """
  4. import sys
  5. import os
  6. import time
  7. import logging
  8. # 修复 macOS 上 Qt 库冲突问题
  9. # 注意:由于 macOS SIP 限制,DYLD_LIBRARY_PATH 必须在启动前设置
  10. # 建议使用 run_mac.sh 脚本启动程序
  11. if sys.platform == 'darwin':
  12. # 设置 Qt 插件路径(如果环境变量未设置)
  13. if 'QT_PLUGIN_PATH' not in os.environ:
  14. try:
  15. import PyQt5
  16. pyqt5_dir = os.path.dirname(PyQt5.__file__)
  17. plugin_path = os.path.join(pyqt5_dir, 'Qt5', 'plugins')
  18. if os.path.exists(plugin_path):
  19. os.environ['QT_PLUGIN_PATH'] = plugin_path
  20. except ImportError:
  21. pass
  22. # 禁用 Anaconda 的 Qt 库加载警告
  23. os.environ.setdefault('QT_MAC_DISABLE_OSX_KEYS', '1')
  24. from PyQt5.QtWidgets import QApplication, QDialog
  25. from PyQt5.QtGui import QIcon
  26. from PyQt5.QtCore import QCoreApplication
  27. from ui.main_window import MainWindow
  28. from ui.login_dialog import LoginDialog
  29. from database import Database, get_base_path
  30. # 配置启动日志
  31. logging.basicConfig(
  32. level=logging.INFO,
  33. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  34. )
  35. startup_logger = logging.getLogger('startup')
  36. def get_icon_path():
  37. """获取图标文件路径"""
  38. base_path = get_base_path()
  39. icon_path = os.path.join(base_path, "logo.ico")
  40. # 如果图标文件不存在,尝试查找其他位置
  41. if not os.path.exists(icon_path):
  42. # 开发环境可能在项目根目录
  43. dev_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logo.ico")
  44. if os.path.exists(dev_path):
  45. icon_path = dev_path
  46. # 尝试从exe文件路径获取
  47. if not os.path.exists(icon_path):
  48. exe_dir = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else None
  49. if exe_dir:
  50. exe_icon_path = os.path.join(exe_dir, "logo.ico")
  51. if os.path.exists(exe_icon_path):
  52. icon_path = exe_icon_path
  53. return icon_path if os.path.exists(icon_path) else None
  54. def main():
  55. """主函数"""
  56. start_time = time.time()
  57. startup_logger.info("=" * 60)
  58. startup_logger.info("🚀 程序启动开始")
  59. startup_logger.info("=" * 60)
  60. step_start = time.time()
  61. startup_logger.info("📱 步骤1: 创建 QApplication...")
  62. # macOS 上确保使用正确的 Qt 插件路径
  63. if sys.platform == 'darwin':
  64. plugin_path = os.environ.get('QT_PLUGIN_PATH')
  65. if plugin_path and os.path.exists(plugin_path):
  66. QCoreApplication.setLibraryPaths([plugin_path])
  67. startup_logger.info(f" 📍 使用 Qt 插件路径: {plugin_path}")
  68. app = QApplication(sys.argv)
  69. startup_logger.info(f" ✅ QApplication 创建完成 (耗时: {time.time() - step_start:.3f}秒)")
  70. # 优先设置应用程序图标(必须在创建任何窗口之前设置)
  71. # 这对Windows任务栏图标至关重要
  72. step_start = time.time()
  73. startup_logger.info("🎨 步骤2: 设置应用程序图标...")
  74. icon_path = get_icon_path()
  75. if icon_path:
  76. icon = QIcon(icon_path)
  77. app.setWindowIcon(icon)
  78. # 设置应用程序ID(Windows 7+任务栏图标识别)
  79. if sys.platform == 'win32':
  80. try:
  81. import ctypes
  82. # 设置应用程序用户模型ID,帮助Windows正确识别程序图标
  83. app_id = '地磅称重打印软件.1.0'
  84. ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(app_id)
  85. except Exception:
  86. pass
  87. startup_logger.info(f" ✅ 图标设置完成 (耗时: {time.time() - step_start:.3f}秒)")
  88. else:
  89. startup_logger.info(f" ⚠️ 未找到图标文件 (耗时: {time.time() - step_start:.3f}秒)")
  90. # 设置应用程序样式
  91. step_start = time.time()
  92. startup_logger.info("🎨 步骤3: 设置应用程序样式...")
  93. app.setStyle('Fusion')
  94. startup_logger.info(f" ✅ 样式设置完成 (耗时: {time.time() - step_start:.3f}秒)")
  95. step_start = time.time()
  96. startup_logger.info("💾 步骤4: 初始化数据库连接...")
  97. db = Database()
  98. startup_logger.info(f" ✅ 数据库初始化完成 (耗时: {time.time() - step_start:.3f}秒)")
  99. step_start = time.time()
  100. startup_logger.info("🔐 步骤5: 创建登录对话框...")
  101. login_dialog = LoginDialog(db)
  102. startup_logger.info(f" ✅ 登录对话框创建完成 (耗时: {time.time() - step_start:.3f}秒)")
  103. step_start = time.time()
  104. startup_logger.info("👤 步骤6: 显示登录对话框,等待用户登录...")
  105. login_result = login_dialog.exec_()
  106. startup_logger.info(f" ✅ 登录对话框关闭 (耗时: {time.time() - step_start:.3f}秒)")
  107. if login_result == QDialog.Accepted and login_dialog.logged_in_user:
  108. step_start = time.time()
  109. startup_logger.info("🖥️ 步骤7: 创建主窗口...")
  110. window = MainWindow(db=db, current_user=login_dialog.logged_in_user)
  111. startup_logger.info(f" ✅ 主窗口创建完成 (耗时: {time.time() - step_start:.3f}秒)")
  112. step_start = time.time()
  113. startup_logger.info("📺 步骤8: 显示主窗口...")
  114. window.showMaximized() # 登录后自动最大化主界面
  115. startup_logger.info(f" ✅ 主窗口显示完成 (耗时: {time.time() - step_start:.3f}秒)")
  116. total_time = time.time() - start_time
  117. startup_logger.info("=" * 60)
  118. startup_logger.info(f"🎉 程序启动完成!总耗时: {total_time:.3f}秒")
  119. startup_logger.info("=" * 60)
  120. sys.exit(app.exec_())
  121. else:
  122. total_time = time.time() - start_time
  123. startup_logger.info("=" * 60)
  124. startup_logger.info(f"❌ 用户取消登录,程序退出。总耗时: {total_time:.3f}秒")
  125. startup_logger.info("=" * 60)
  126. sys.exit(0)
  127. if __name__ == '__main__':
  128. main()