mainwindow.cpp

Go to the documentation of this file.
00001 
00002 #include "appconfig.h"
00003 
00004 #include "main.h"
00005 #include "mainwindow.h"
00006 #include "printpreview.h"
00007 
00008 extern appconfig mytetraconfig;
00009 
00010 
00011 mainwindow::mainwindow() : QMainWindow()
00012 {
00013  setup_ui();
00014  setup_signals();
00015  assembly();
00016 
00017  initFileActions();
00018  
00019  setup_icon_actions();
00020  create_tray_icon();
00021  set_icon();
00022 
00023  tray_icon->show();
00024 }
00025 
00026 
00027 mainwindow::~mainwindow()
00028 {
00029  // При удалении главного окна надо сохранить данные в поле редактирования
00030  save_current_record_text();
00031 
00032  // Сохраняются данные сеанса работы
00033  save_geometry();
00034  save_tree_position();
00035  save_recordtable_position();
00036   
00037  delete treeview;
00038  delete recordtableview;
00039  delete editorview;
00040 }
00041 
00042 
00043 void mainwindow::setup_ui(void)
00044 {
00045  treeview=new treescreen;
00046  treeview->setObjectName("treeview");
00047 
00048  recordtableview=new recordtablescreen();
00049  recordtableview->setObjectName("recordtableview");
00050 
00051  editorview=new metaeditor();
00052  editorview->setObjectName("editorview");
00053 
00054  findscreendisp=new findscreen();
00055  findscreendisp->setObjectName("findscreendisp");
00056 
00057  statbar=new QStatusBar();
00058  statbar->setObjectName("statbar");
00059  setStatusBar(statbar);
00060 
00061 }
00062 
00063 
00064 void mainwindow::setup_signals(void)
00065 {
00066 
00067 }
00068 
00069 
00070 void mainwindow::assembly(void)
00071 {
00072  vspl=new QSplitter(Qt::Vertical);
00073  vspl->addWidget(recordtableview); // Список конечных записей
00074  vspl->addWidget(editorview); // Содержимое записи
00075  vspl->setCollapsible(0,false); // Список конечных записей не может смыкаться
00076  vspl->setCollapsible(1,false); // Содержимое записи не может смыкаться
00077 
00078  hspl=new QSplitter(Qt::Horizontal);
00079  hspl->addWidget(treeview); // Дерево информационных групп
00080  hspl->addWidget(vspl);
00081  hspl->setCollapsible(0,false); // Дерево информационных групп не может смыкаться
00082  hspl->setCollapsible(1,false); // Столбец со списком и содержимым записи не может смыкаться
00083 
00084  findsplitter=new QSplitter(Qt::Vertical);
00085  findsplitter->addWidget(hspl);
00086  findsplitter->addWidget(findscreendisp);
00087  findsplitter->setCollapsible(0,false); // Верхняя часть не должна смыкаться
00088  findsplitter->setCollapsible(1,false); // Часть для поиска не должна смыкаться
00089  findsplitter->setObjectName("findsplitter");
00090  
00091  setCentralWidget(findsplitter);
00092 }
00093 
00094 
00095 // Восстанавливается геометрия окна и позиции основных разделителей
00096 void mainwindow::restore_geometry(void)
00097 {
00098  QRect rect=mytetraconfig.get_mainwingeometry();
00099  move(rect.topLeft());
00100  resize(rect.size());
00101  
00102  vspl->setSizes(mytetraconfig.get_vspl_size_list());
00103  hspl->setSizes(mytetraconfig.get_hspl_size_list());
00104  findsplitter->setSizes(mytetraconfig.get_findsplitter_size_list());
00105 }
00106 
00107 
00108 // Запоминается геометрия окна и позиции основных разделителей
00109 void mainwindow::save_geometry(void)
00110 {
00111  mytetraconfig.set_mainwingeometry(geometry().x(), geometry().y(), 
00112                                    geometry().width(), geometry().height());
00113  
00114  mytetraconfig.set_vspl_size_list(vspl->sizes());
00115  mytetraconfig.set_hspl_size_list(hspl->sizes());
00116  
00117  // Запоминается размер сплиттера только при видимом виджете поиска,
00118  // т.к. если виджета поиска невидно, будет запомнен нуливой размер
00119  if(findscreendisp->isVisible())
00120   mytetraconfig.set_findsplitter_size_list(findsplitter->sizes());
00121 }
00122 
00123 
00124 void mainwindow::restore_tree_position(void)
00125 {
00126  // Путь к последнему выбранному в дереве элементу
00127  QStringList path=mytetraconfig.get_tree_position();
00128 
00129  set_tree_position(path);
00130 }
00131 
00132 
00133 void mainwindow::save_tree_position(void)
00134 {
00135  // Получение QModelIndex выделенного в дереве элемента
00136  QModelIndex index=treeview->get_current_item_index();
00137  
00138  // Получаем указатель вида TreeItem
00139  TreeItem *item =treeview->kntrmodel->getItem(index);
00140 
00141  // Сохраняем путь к элементу item
00142  mytetraconfig.set_tree_position(item->get_path());
00143 }
00144  
00145 
00146 void mainwindow::set_tree_position(QStringList path)
00147 {
00148  // Получаем указатель на элемент вида TreeItem, используя путь
00149  TreeItem *item =treeview->kntrmodel->getItem(path);
00150  
00151  qDebug() << "Set tree position to " << item->data("name") << " id " << item->data("id");
00152  
00153  // Из указателя на элемент TreeItem получаем QModelIndex
00154  QModelIndex setto=treeview->kntrmodel->get_item_index(item);
00155 
00156  // Курсор устанавливается в нужную позицию
00157  treeview->set_cursor_to_index(setto);
00158 }
00159 
00160 
00161 void mainwindow::restore_recordtable_position(void)
00162 {
00163  int n=mytetraconfig.get_recordtable_position();
00164  
00165  set_recordtable_position(n);
00166 }
00167 
00168 
00169 void mainwindow::save_recordtable_position(void)
00170 {
00171  int n=recordtableview->get_first_selection_pos();
00172  
00173  mytetraconfig.set_recordtable_position(n);
00174 }
00175 
00176 
00177 void mainwindow::set_recordtable_position(int n)
00178 {
00179  recordtableview->set_selection_to_pos(n);
00180 }
00181 
00182 
00183 void mainwindow::restore_findonbase_visible(void)
00184 {
00185  bool n=mytetraconfig.get_findscreen_show();
00186 
00187  // Определяется ссылка на виджет поиска
00188  findscreen *findscreen_rel=find_object<findscreen>("findscreendisp");
00189  
00190  if(n)
00191   findscreen_rel->show();
00192  else
00193   findscreen_rel->hide();
00194 }
00195 
00196 
00197 // Создание раздела меню File
00198 void mainwindow::initFileActions(void)
00199  {
00200      // Создание меню
00201      QMenu *menu = new QMenu(tr("&File"), this);
00202      menuBar()->addMenu(menu);
00203 
00204      // Создание тулбара
00205      /*
00206      QToolBar *tb = new QToolBar(this);
00207      tb->setWindowTitle(tr("File Actions"));
00208      addToolBar(tb);
00209      */
00210 
00211      QAction *a;
00212 
00213      a = new QAction(tr("&New"), this);
00214      a->setShortcut(QKeySequence::New);
00215      connect(a, SIGNAL(triggered()), this, SLOT(fileNew()));
00216      // tb->addAction(a);
00217      menu->addAction(a);
00218 
00219      a = new QAction(tr("&Open..."), this);
00220      a->setShortcut(QKeySequence::Open);
00221      connect(a, SIGNAL(triggered()), this, SLOT(fileOpen()));
00222      // tb->addAction(a);
00223      menu->addAction(a);
00224 
00225      menu->addSeparator();
00226 
00227      a = new QAction(tr("&Save"), this);
00228      a->setShortcut(QKeySequence::Save);
00229      connect(a, SIGNAL(triggered()), this, SLOT(fileSave()));
00230      a->setEnabled(false);
00231      // tb->addAction(a);
00232      menu->addAction(a);
00233 
00234      a = new QAction(tr("Save &As..."), this);
00235      connect(a, SIGNAL(triggered()), this, SLOT(fileSaveAs()));
00236      menu->addAction(a);
00237      menu->addSeparator();
00238 
00239      a = new QAction(tr("&Print..."), this);
00240      a->setShortcut(QKeySequence::Print);
00241      connect(a, SIGNAL(triggered()), this, SLOT(filePrint()));
00242      // tb->addAction(a);
00243      menu->addAction(a);
00244 
00245      a = new QAction(tr("Print Preview..."), this);
00246      connect(a, SIGNAL(triggered()), this, SLOT(filePrintPreview()));
00247      menu->addAction(a);
00248 
00249      a = new QAction(tr("&Export PDF..."), this);
00250      a->setShortcut(Qt::CTRL + Qt::Key_D);
00251      connect(a, SIGNAL(triggered()), this, SLOT(filePrintPdf()));
00252      // tb->addAction(a);
00253      menu->addAction(a);
00254 
00255      menu->addSeparator();
00256 
00257      a = new QAction(tr("&Quit"), this);
00258      a->setShortcut(Qt::CTRL + Qt::Key_Q);
00259      connect(a, SIGNAL(triggered()), this, SLOT(application_exit()));
00260      menu->addAction(a);
00261  }
00262 
00263 // Новая коллекция
00264 void mainwindow::fileNew(void)
00265 {
00266 
00267 }
00268 
00269 // Открыть коллекцию
00270 void mainwindow::fileOpen(void)
00271 {
00272 
00273 }
00274 
00275 // Сохранить текущую статью
00276 bool mainwindow::fileSave(void)
00277 {
00278  return true;
00279 }
00280 
00281 // Сохранить текущую статью как файл
00282 bool mainwindow::fileSaveAs(void)
00283 {
00284  return true;
00285 }
00286 
00287 // Напечатать текущую статью
00288 void mainwindow::filePrint(void)
00289 {
00290 #ifndef QT_NO_PRINTER
00291      QPrinter printer(QPrinter::HighResolution);
00292      printer.setFullPage(true);
00293      QPrintDialog *dlg = new QPrintDialog(&printer, this);
00294      dlg->setWindowTitle(tr("Print Document"));
00295      if (dlg->exec() == QDialog::Accepted) {
00296          editorview->textarea->document()->print(&printer);
00297      }
00298      delete dlg;
00299 #endif
00300 }
00301 
00302 // Предпросмотр печати текущей статьи
00303 void mainwindow::filePrintPreview(void){
00304      PrintPreview *preview = new PrintPreview(editorview->textarea->document(), this);
00305      preview->setWindowModality(Qt::WindowModal);
00306      preview->setAttribute(Qt::WA_DeleteOnClose);
00307      preview->show();
00308 }
00309 
00310 // Вывод текущей статьи в PDF файл
00311 void mainwindow::filePrintPdf(void)
00312 {
00313 #ifndef QT_NO_PRINTER
00314      QString fileName = QFileDialog::getSaveFileName(this, "Export PDF",
00315                                                      QString(), "*.pdf");
00316      if (!fileName.isEmpty()) {
00317          if (QFileInfo(fileName).suffix().isEmpty())
00318              fileName.append(".pdf");
00319          QPrinter printer(QPrinter::HighResolution);
00320          printer.setOutputFormat(QPrinter::PdfFormat);
00321          printer.setOutputFileName(fileName);
00322          editorview->textarea->document()->print(&printer);
00323      }
00324 #endif
00325 }
00326 
00327 
00328 void mainwindow::application_exit(void)
00329 {
00330  exit(0);
00331 }
00332 
00333 
00334 void mainwindow::setup_icon_actions(void)
00335 {
00336  tray_restore_action = new QAction(tr("&Restore window"), this);
00337  connect(tray_restore_action, SIGNAL(triggered()), this, SLOT(showNormal()));
00338 
00339  tray_maximize_action = new QAction(tr("Ma&ximize window"), this);
00340  connect(tray_maximize_action, SIGNAL(triggered()), this, SLOT(showMaximized()));
00341 
00342  tray_minimize_action = new QAction(tr("Mi&nimize window"), this);
00343  connect(tray_minimize_action, SIGNAL(triggered()), this, SLOT(hide()));
00344 
00345  tray_quit_action = new QAction(tr("&Quit"), this);
00346  connect(tray_quit_action, SIGNAL(triggered()), qApp, SLOT(quit()));
00347 }
00348 
00349 
00350 void mainwindow::create_tray_icon(void)
00351 {
00352  tray_icon_menu = new QMenu(this);
00353  tray_icon_menu->addAction(tray_restore_action);
00354  tray_icon_menu->addAction(tray_maximize_action);
00355  tray_icon_menu->addAction(tray_minimize_action);
00356  tray_icon_menu->addSeparator();
00357  tray_icon_menu->addAction(tray_quit_action);
00358 
00359  tray_icon = new QSystemTrayIcon(this);
00360  tray_icon->setContextMenu(tray_icon_menu);
00361 }
00362 
00363 
00364 void mainwindow::set_icon(void)
00365 {
00366  connect(tray_icon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
00367          this, SLOT(icon_activated(QSystemTrayIcon::ActivationReason)));
00368 
00369  
00370  QIcon icon = QIcon(":/resource/pic/logo.svg");
00371  tray_icon->setIcon(icon);
00372  setWindowIcon(icon);
00373 
00374  // tray_icon->setToolTip(iconComboBox->itemText(index));
00375 }
00376 
00377 
00378 void mainwindow::icon_activated(QSystemTrayIcon::ActivationReason reason)
00379 {
00380     switch (reason) 
00381      {
00382       case QSystemTrayIcon::Trigger:
00383       case QSystemTrayIcon::DoubleClick:
00384            if(isVisible())
00385             {
00386              if(isMinimized()) showNormal();
00387              else hide();
00388             } 
00389            else 
00390             {
00391              if(isMinimized()) showNormal();
00392              else show();
00393            } 
00394       default:
00395            ; 
00396      }
00397 }
00398 
00399 
00400 // Слот закрытия окна
00401 void mainwindow::closeEvent(QCloseEvent *event)
00402 {
00403  // При приходе события закрыть окно, событие игнорируется 
00404  // и окно просто делается невидимым. Это нужно чтобы при закрытии окна
00405  // программа не завершала работу
00406  if (tray_icon->isVisible()) 
00407   {
00408    hide();
00409    event->ignore();
00410   }
00411 }
00412 
00413 
00414 // Функция cохранения текущей записи на экране
00415 void mainwindow::save_current_record_text(void)
00416 {
00417  // Текст в окне редактирования
00418  QTextDocument *doc=editorview->textarea->document();
00419 
00420  // qDebug() << "Save record from dir " << recordtableview->get_currentdir() << " file " << recordtableview->get_currentfile() ;
00421  // qDebug() << (recordtableview->get_currentdir()).length() << " " << (recordtableview->get_currentfile()).length();
00422  
00423  // Если запись была открыта на просмотр и изменена
00424  if((recordtableview->get_currentdir()).length()!=0 &&
00425     (recordtableview->get_currentfile()).length()!=0 &&
00426     doc->isModified()==true)
00427   {
00428    // Перенос текущего файла записи в резервную директорию
00429    QString filenamefrom=recordtableview->get_fullfilename_of_currentitem();
00430    QString filenameto  =mytetraconfig.get_trashdir()+"/"+mytetraconfig.get_lastprefixnum_as_line()+"_"+recordtableview->get_currentfile();
00431    mytetraconfig.inc_lastprefixnum();
00432    qDebug() << "Move file from " << filenamefrom << " to " << filenameto;
00433    QFile::rename(filenamefrom,filenameto);
00434 
00435   // Создание нового файла записи
00436    QFile wfile(recordtableview->get_fullfilename_of_currentitem());
00437 
00438    if (!wfile.open(QIODevice::WriteOnly | QIODevice::Text))
00439     {
00440      qDebug() << "Cant open file " << recordtableview->get_fullfilename_of_currentitem() << " for write.";
00441      exit(1);
00442     }
00443 
00444    qDebug() << "Write changed info to file " << recordtableview->get_fullfilename_of_currentitem();
00445 
00446    // QTextStream out(&wfile);
00447    // QString content=editorview->textarea->toHtml();
00448    // out.setCodec("UTF-8");
00449    // out << content;
00450 
00451    QTextStream out(&wfile);
00452    QString content=editorview->textarea->document()->toHtml("UTF-8");
00453    out.setCodec("UTF-8");
00454    out << content;
00455 
00456  }
00457 
00458  // Отмечается в документе что новый текст небыл еще изменен
00459  doc->setModified(false);
00460 }
00461 
00462 
00463 

Generated on Mon Feb 2 00:25:34 2009 for mytetra by  doxygen 1.5.1