Debian Codegraph @

src/qbrew.cpp

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 /***************************************************************************
2 qbrew.cpp
3 -------------------
4 Control class for QBrew
5 -------------------
6 Copyright 2006-2008 David Johnson
7 Please see the header file for copyright and license information.
8 ***************************************************************************/
9
10 #include <QtGui>
11
12 #include "alcoholtool.h"
13 #include "configure.h"
14 #include "data.h"
15 #include "databasetool.h"
16 #include "recipe.h"
17 #include "helpviewer.h"
18 #include "hydrometertool.h"
19 #include "resource.h"
20 #include "textprinter.h"
21 #include "view.h"
22
23 #include "qbrew.h"
24
25 using namespace Resource;
26
27 QBrew *QBrew::instance_ = 0;
28 static QMutex instancelock;
29
30 //////////////////////////////////////////////////////////////////////////////
31 // Construction, Destruction, Initialization //
32 //////////////////////////////////////////////////////////////////////////////
33
34 //////////////////////////////////////////////////////////////////////////////
35 // QBrew()
36 // ------------
37 // Private constructor
38
39 QBrew::QBrew()
40 : data_(0), recipe_(0), view_(0), alcoholtool_(0), databasetool_(0),
41 hydrometertool_(0), configure_(0), handbook_(0), primer_(0), state_(),
42 filename_(), newflag_(false), backed_(false), autosave_(0),
43 autosavename_(), textprinter_(0)
44 { ; }
45
46 //////////////////////////////////////////////////////////////////////////////
47 // initialize()
48 // ------------
49 // Initialize mainwindow
50
51 void QBrew::initialize(const QString &filename)
52 {
53 setAttribute(Qt::WA_DeleteOnClose);
54 readConfig();
55
56 // show splashscreen
57 if (state_.general.showsplash
58 && QFile::exists(dataBase() + tr("splash.png"))) {
59 QSplashScreen *splash = new QSplashScreen(dataBase() + tr("splash.png"),
60 Qt::WindowStaysOnTopHint);
61 splash->show();
62 QApplication::flush();
63 QTimer::singleShot(3000, splash, SLOT(close()));
64 }
65
66 // setup look and feel
67 setWindowIcon(QIcon(":/pics/qbrew.png"));
68 if ((state_.general.lookfeel != QApplication::style()->objectName()) &&
69 (QStyleFactory::keys().contains(state_.general.lookfeel))) {
70 QApplication::setStyle(state_.general.lookfeel);
71 }
72
73 // setup UI
74 ui.setupUi(this);
75 initActions();
76 #if defined (Q_WS_MAC)
77 // initial defaults for mac
78 setUnifiedTitleAndToolBarOnMac(false);
79 ui.maintoolbar->setVisible(false);
80 #endif
81
82 // restore window state
83 restoreState();
84
85 // initialize data
86 data_ = Data::instance();
87 data_->initialize(state_);
88
89 // initialize calculations
90 data_->setSteepYield(state_.calc.steepyield);
91 data_->setTinseth(state_.calc.tinseth);
92 data_->setMorey(state_.calc.morey);
93
94 // create recipe
95 recipe_ = new Recipe(this);
96 connect(recipe_, SIGNAL(recipeModified()), this, SLOT(recipeModified()));
97
98 // create view
99 view_ = new View(this, recipe_);
100
101 // load or create a recipe
102 bool emptyfilename = (filename.isEmpty() ||
103 (filename == tr(DEFAULT_FILE)));
104 if (emptyfilename &&
105 (state_.general.loadlast && !state_.general.recentfiles.isEmpty())) {
106 if (QFile::exists(state_.general.recentfiles.first())) {
107 filename_ = state_.general.recentfiles.first();
108 }
109 } else {
110 filename_ = filename;
111 }
112 emptyfilename = (filename_.isEmpty() ||
113 (filename_ == tr(DEFAULT_FILE)));
114 if (!emptyfilename) {
115 openFile(filename_);
116 } else {
117 recipe_->newRecipe();
118 newflag_ = true;
119 backed_ = false;
120 filename_ = tr(DEFAULT_FILE) + "." + FILE_EXT;
121 setWindowTitle(TITLE + " " + VERSION + " [*]");
122 }
123
124 // connections
125 connect(ui.menuopenrecent, SIGNAL(aboutToShow()),
126 this, SLOT(recentMenuShow()));
127
128 // other initialization
129 initAutoSave();
130 setCentralWidget(view_);
131 view_->refresh();
132 textprinter_ = new TextPrinter(this);
133 }
134
135 //////////////////////////////////////////////////////////////////////////////
136 // ~QBrew()
137 // -------------
138 // Private destructor
139
140 QBrew::~QBrew()
141 {
142 saveState();
143
144 // make sure any open windows are closed
145 if (alcoholtool_) alcoholtool_->close();
146 if (hydrometertool_) hydrometertool_->close();
147 if (databasetool_) databasetool_->close();
148 if (configure_) configure_->close();
149 if (handbook_) handbook_->close();
150 if (primer_) primer_->close();
151 }
152
153 //////////////////////////////////////////////////////////////////////////////
154 // instance()
155 // ----------
156 // Return pointer to the instance
157
158 QBrew *QBrew::instance()
159 {
160 if (!instance_) {
161 QMutexLocker lock(&instancelock);
162 if (!instance_) instance_ = new QBrew();
163 }
164 return instance_;
165 }
166
167 //////////////////////////////////////////////////////////////////////////////
168 // initActions()
169 // -------------
170 // Initialize the actions
171
172 void QBrew::initActions()
173 {
174 connect(ui.actionfilenew, SIGNAL(triggered()),
175 this, SLOT(fileNew()));
176 connect(ui.actionfileopen, SIGNAL(triggered()),
177 this, SLOT(fileOpen()));
178 connect(ui.actionfilesave, SIGNAL(triggered()),
179 this, SLOT(fileSave()));
180 connect(ui.actionfilesaveas, SIGNAL(triggered()),
181 this, SLOT(fileSaveAs()));
182 connect(ui.actionfileprintpreview, SIGNAL(triggered()),
183 this, SLOT(filePrintPreview()));
184 connect(ui.actionfileprint, SIGNAL(triggered()),
185 this, SLOT(filePrint()));
186 connect(ui.actionfileexport, SIGNAL(triggered()),
187 this, SLOT(fileExport()));
188 connect(ui.actionexit, SIGNAL(triggered()), qApp,
189 SLOT(closeAllWindows()));
190
191 connect(ui.actionalcoholtool, SIGNAL(triggered()),
192 this, SLOT(toolsAlcohol()));
193 connect(ui.actionhydrometertool, SIGNAL(triggered()),
194 this, SLOT(toolsHydrometer()));
195 connect(ui.actiondatabasetool, SIGNAL(triggered()),
196 this, SLOT(toolsDatabase()));
197
198 connect(ui.actiontogglestatusbar, SIGNAL(toggled(bool)),
199 this, SLOT(optionsStatusbar(bool)));
200 connect(ui.actionconfigure, SIGNAL(triggered()),
201 this, SLOT(optionsConfigure()));
202
203 connect(ui.actionhelpcontents, SIGNAL(triggered()),
204 this, SLOT(helpContents()));
205 connect(ui.actionprimer, SIGNAL(triggered()),
206 this, SLOT(helpPrimer()));
207 connect(ui.actioncontexthelp, SIGNAL(triggered()),
208 this, SLOT(helpContext()));
209 connect(ui.actionabout, SIGNAL(triggered()), this, SLOT(helpAbout()));
210
211 #if (QT_VERSION < QT_VERSION_CHECK(4, 4, 0))
212 ui.actionfileprintpreview->setVisible(false);
213 #endif
214
215 // insert toolbar toggle action
216 ui.maintoolbar->toggleViewAction()->setStatusTip(tr("Toggle the toolbar"));
217 ui.maintoolbar->toggleViewAction()->setWhatsThis(tr("Enable or disable the Toolbar"));
218 ui.menuoptions->insertAction(ui.actiontogglestatusbar,
219 ui.maintoolbar->toggleViewAction());
220 }
221
222 //////////////////////////////////////////////////////////////////////////////
223 // initAutoSave()
224 // ---------------
225 // Initialize the autosave timer
226
227 void QBrew::initAutoSave()
228 {
229 // destroy existing timer, if any
230 if (autosave_) {
231 autosave_->stop();
232 disconnect(autosave_, SIGNAL(timeout()), this, SLOT(autoSave()));
233 delete autosave_; autosave_ = 0;
234 }
235
236 autosavename_ = QDir::currentPath() + tr("/autosave.") + FILE_EXT;
237
238 if (state_.general.autosave) {
239 autosave_ = new QTimer(this);
240 connect(autosave_, SIGNAL(timeout()), this, SLOT(autoSave()));
241 autosave_->start(state_.general.saveinterval * 60000);
242 }
243 }
244
245 //////////////////////////////////////////////////////////////////////////////
246 // File Menu Implementation //
247 //////////////////////////////////////////////////////////////////////////////
248
249 //////////////////////////////////////////////////////////////////////////////
250 // fileNew()
251 // ---------
252 // Create a new recipe
253
254 void QBrew::fileNew()
255 {
256 if (recipe_->modified()) {
257 // query user to save file
258 switch (querySave()) {
259 case QMessageBox::Yes:
260 fileSave();
261 break;
262 case QMessageBox::No:
263 break;
264 case QMessageBox::Cancel:
265 statusBar()->showMessage(tr("Canceled..."), 2000);
266 // exit function
267 return;
268 }
269 }
270
271 // create a new file
272 recipe_->newRecipe();
273 newflag_ = true;
274 backed_ = false;
275
276 ui.actionfilesave->setEnabled(true);
277
278 filename_ = tr(DEFAULT_FILE);
279 setFileCaption(filename_);
280 statusBar()->showMessage(tr("Created new recipe"), 2000);
281 }
282
283 //////////////////////////////////////////////////////////////////////////////
284 // fileOpen()
285 // ----------
286 // Open a recipe
287
288 void QBrew::fileOpen(const QString &filename)
289 {
290 if (recipe_->modified()) {
291 // query user to save file
292 switch (querySave()) {
293 case QMessageBox::Yes:
294 fileSave();
295 break;
296 case QMessageBox::No:
297 break;
298 case QMessageBox::Cancel:
299 statusBar()->showMessage(tr("Canceled..."), 2000);
300 return;
301 }
302 }
303
304 // open the file
305 statusBar()->showMessage(tr("Opening recipe..."));
306 QString fname;
307 if (filename.isEmpty()) {
308 fname = QFileDialog::getOpenFileName(this,
309 tr("Open..."),
310 QString(),
311 tr(OPEN_FILTER));
312 } else {
313 fname = filename;
314 }
315 if (openFile(fname)) {
316 statusBar()->showMessage(tr("Loaded recipe"), 2000);
317 } else {
318 statusBar()->showMessage(tr("Load failed"), 2000);
319 }
320 }
321
322 //////////////////////////////////////////////////////////////////////////////
323 // fileRecent()
324 // -----------
325 // Selection has been made from recent file menu
326
327 void QBrew::fileRecent()
328 {
329 QAction *action = qobject_cast<QAction *>(sender());
330 if (!action) return;
331
332 if (recipe_->modified()) {
333 // file needs to be saved, what do we do
334 switch (querySave()) {
335 case QMessageBox::Yes:
336 fileSave();
337 break;
338 case QMessageBox::No:
339 break;
340 case QMessageBox::Cancel:
341 statusBar()->showMessage(tr("Canceled..."), 2000);
342 return;
343 }
344 }
345
346 // open the file
347 QString fname = action->text();
348 if (openFile(fname)) {
349 statusBar()->showMessage(tr("Loaded recipe"), 2000);
350 addRecent(fname);
351 }
352 }
353
354 //////////////////////////////////////////////////////////////////////////////
355 // fileSave()
356 // ----------
357 // Save a recipe
358
359 void QBrew::fileSave()
360 {
361 if (newflag_) {
362 fileSaveAs();
363 } else {
364 if (state_.general.autobackup) {
365 if (!backupFile())
366 QMessageBox::warning(this, TITLE,
367 tr("%1 was unable to make a backup of %2")
368 .arg(PACKAGE).arg(filename_));
369 }
370 if (saveFile(filename_)) {
371 // successful in saving file
372 newflag_ = false;
373 ui.actionfilesave->setEnabled(false);
374 setFileCaption(filename_);
375 statusBar()->showMessage(tr("Saved recipe"), 2000);
376 } else {
377 // error in saving file
378 QMessageBox::warning(this, TITLE,
379 tr("%1 was unable to save %2")
380 .arg(PACKAGE).arg(filename_));
381 statusBar()->showMessage(tr("Error in saving recipe"), 2000);
382 }
383 }
384 }
385
386 //////////////////////////////////////////////////////////////////////////////
387 // fileSaveAs()
388 // ------------
389 // Save a recipe under a new name
390
391 void QBrew::fileSaveAs()
392 {
393 statusBar()->showMessage(tr("Saving recipe under new filename..."));
394 QString selected;
395 QString fname;
396 fname = QFileDialog::getSaveFileName(this,
397 tr("Save As..."),
398 QString(),
399 tr(SAVE_FILTER),
400 &selected,
401 QFileDialog::DontConfirmOverwrite);
402 if (!fname.isEmpty()) { // we got a filename
403 // add suffix if there is none
404 if (!QFile::exists(fname)) {
405 if (fname.indexOf('.') == -1) fname += '.' + FILE_EXT;
406 }
407
408 if (state_.general.autobackup) backupFile();
409 if (QFile::exists(fname)) {
410 // overwrite?
411 switch (queryOverwrite(fname)) {
412 case QMessageBox::Yes:
413 break;
414 case QMessageBox::Cancel:
415 statusBar()->showMessage(tr("Canceled..."), 2000);
416 return;
417 }
418 }
419
420 if (saveFile(fname)) {
421 // successfully saved
422 newflag_ = false;
423 addRecent(fname);
424 ui.actionfilesave->setEnabled(false);
425 setFileCaption(fname);
426 statusBar()->showMessage(tr("Saved recipe"), 2000);
427 // save name of file
428 filename_ = fname;
429 } else {
430 // error in saving
431 QMessageBox::warning(this, TITLE,
432 tr("Unable to save to %1")
433 .arg(QFileInfo(filename_).fileName()));
434 statusBar()->showMessage(tr("Error in saving recipe"), 2000);
435 }
436 } else {
437 // no file chosen
438 statusBar()->showMessage(tr("Saving aborted"), 2000);
439 }
440 }
441
442 //////////////////////////////////////////////////////////////////////////////
443 // fileExport()
444 // ------------
445 // Export recipe to non-native format
446
447 void QBrew::fileExport()
448 {
449 bool status = false;
450 QString selected;
451 QString fname;
452 QString dirfile;
453
454 fname = QFileDialog::getSaveFileName(this,
455 tr("Export..."),
456 QString(),
457 tr(EXPORT_FILTER),
458 &selected,
459 QFileDialog::DontConfirmOverwrite);
460
461 if (!fname.isEmpty()) { // we got a filename
462 // add suffix if there is none
463 if (!QFile::exists(fname)) {
464 if (fname.indexOf('.') == -1) {
465 if (selected == tr(HTML_FILTER)) fname += ".html";
466 else if (selected == tr(BEERXML_FILTER)) fname += ".xml";
467 else if (selected == tr(PDF_FILTER)) fname += ".pdf";
468 else if (selected == tr(TEXT_FILTER)) fname += ".txt";
469 }
470 }
471
472 if (QFile::exists(fname)) {
473 // overwrite?
474 switch (queryOverwrite(fname)) {
475 case QMessageBox::Yes:
476 break;
477 case QMessageBox::Cancel:
478 statusBar()->showMessage(tr("Canceled..."), 2000);
479 return;
480 }
481 }
482
483 // export recipe
484 if (selected == tr(HTML_FILTER)) {
485 status = recipe_->exportHtml(fname);
486 } else if (selected == tr(BEERXML_FILTER)) {
487 status = recipe_->exportBeerXML(fname);
488 } else if (selected == tr(PDF_FILTER)) {
489 status = recipe_->exportPdf(textprinter_, fname);
490 } else if (selected == tr(TEXT_FILTER)) {
491 status = recipe_->exportText(fname);
492 }
493 if (status) {
494 // successfully exported
495 statusBar()->showMessage(tr("Exported recipe"), 2000);
496 } else {
497 // error in exporting
498 QMessageBox::warning(this, TITLE,
499 tr("Unable to export to %1")
500 .arg(QFileInfo(filename_).fileName()));
501 statusBar()->showMessage(tr("Error exporting recipe"), 2000);
502 }
503 } else {
504 // no file chosen
505 statusBar()->showMessage(tr("Export aborted"), 2000 );
506 }
507 }
508
509 //////////////////////////////////////////////////////////////////////////////
510 // filePrintPreview()
511 // ------------
512 // Print the recipe
513
514 void QBrew::filePrintPreview()
515 {
516 statusBar()->showMessage(tr("Print preview..."));
517
518 recipe_->previewRecipe(textprinter_);
519 statusBar()->showMessage(tr(READY), 2000);
520 }
521
522 //////////////////////////////////////////////////////////////////////////////
523 // filePrint()
524 // ------------
525 // Print the recipe
526
527 void QBrew::filePrint()
528 {
529 statusBar()->showMessage(tr("Printing..."));
530
531 recipe_->printRecipe(textprinter_);
532 statusBar()->showMessage(tr(READY), 2000);
533 }
534
535 //////////////////////////////////////////////////////////////////////////////
536 // Tools Menu Implementation //
537 //////////////////////////////////////////////////////////////////////////////
538
539 //////////////////////////////////////////////////////////////////////////////
540 // toolsAlcohol()
541 // --------------
542 // A utility dialog for alchohol calculation
543
544 void QBrew::toolsAlcohol()
545 {
546 if (!alcoholtool_) alcoholtool_ = new AlcoholTool(this);
547 alcoholtool_->show();
548 alcoholtool_->raise();
549 if (alcoholtool_->isMinimized()) alcoholtool_->showNormal();
550
551 statusBar()->showMessage(tr(READY), 2000);
552 }
553
554 //////////////////////////////////////////////////////////////////////////////
555 // toolsHydrometer()
556 // -----------------
557 // A utility dialog for hydrometer correction
558
559 void QBrew::toolsHydrometer()
560 {
561 if (!hydrometertool_) hydrometertool_ = new HydrometerTool(this);
562 hydrometertool_->show();
563 hydrometertool_->raise();
564 if (hydrometertool_->isMinimized()) hydrometertool_->showNormal();
565
566 statusBar()->showMessage(tr(READY), 2000);
567 }
568
569 //////////////////////////////////////////////////////////////////////////////
570 // toolsDatabase()
571 // ---------------
572 // A database editor for ingredients
573
574 void QBrew::toolsDatabase()
575 {
576 if (!databasetool_)
577 databasetool_ = new DatabaseTool(this);
578 databasetool_->show();
579 databasetool_->raise();
580 if (databasetool_->isMinimized()) databasetool_->showNormal();
581
582 statusBar()->showMessage(tr(READY), 2000);
583 }
584
585 //////////////////////////////////////////////////////////////////////////////
586 // Options Menu Implementation //
587 //////////////////////////////////////////////////////////////////////////////
588
589 //////////////////////////////////////////////////////////////////////////////
590 // optionsSatusbar()
591 // -----------------
592 // Toggle statusbar status
593
594 void QBrew::optionsStatusbar(bool on)
595 {
596 statusBar()->setVisible(on);
597 state_.window.statusbar = on;
598 statusBar()->showMessage(tr(READY), 2000);
599 }
600
601 //////////////////////////////////////////////////////////////////////////////
602 // optionsConfigure()
603 // ------------
604 // Display the configuration dialog
605
606 void QBrew::optionsConfigure()
607 {
608 statusBar()->showMessage(tr("Configuring %1 ...").arg(PACKAGE), 2000);
609
610 if (!configure_) {
611 configure_ = new Configure(this);
612
613 connect(configure_, SIGNAL(generalApply(const GenConfigState&)),
614 this, SLOT(applyGeneralState(const GenConfigState&)));
615 connect(configure_, SIGNAL(recipeApply(const RecipeConfigState&)),
616 this, SLOT(applyRecipeState(const RecipeConfigState&)));
617 connect(configure_, SIGNAL(calcApply(const CalcConfigState&)),
618 this, SLOT(applyCalcState(const CalcConfigState&)));
619 connect(configure_, SIGNAL(configureAccept()),
620 this, SLOT(saveConfig()));
621 }
622
623 if (!configure_->isVisible()) {
624 configure_->setState(state_);
625 }
626 configure_->show(); // non-modal
627 configure_->raise();
628 if (configure_->isMinimized()) configure_->showNormal();
629
630 statusBar()->showMessage(tr(READY), 2000);
631 }
632
633 //////////////////////////////////////////////////////////////////////////////
634 // Help Menu Implementation //
635 //////////////////////////////////////////////////////////////////////////////
636
637 //////////////////////////////////////////////////////////////////////////////
638 // helpContents()
639 // --------------
640 // Display the application manual
641
642 void QBrew::helpContents()
643 {
644 QString home = docBase() + tr(HELP_FILE);
645
646 if (!handbook_) handbook_ = new HelpViewer(home, 0);
647 handbook_->show();
648 handbook_->raise();
649 if (handbook_->isMinimized()) handbook_->showNormal();
650
651 statusBar()->showMessage(tr(READY), 2000);
652 }
653
654 //////////////////////////////////////////////////////////////////////////////
655 // helpPrimer()
656 // --------------
657 // Display the brewing primer
658
659 void QBrew::helpPrimer()
660 {
661 QString home = docBase() + tr(PRIMER_FILE);
662
663 if (!primer_) primer_ = new HelpViewer(home, 0);
664 primer_->show();
665 primer_->raise();
666 if (primer_->isMinimized()) primer_->showNormal();
667
668 statusBar()->showMessage(tr(READY), 2000);
669 }
670
671 //////////////////////////////////////////////////////////////////////////////
672 // helpContext()
673 // -------------
674 // Display context help cursor
675
676 void QBrew::helpContext()
677 {
678 QWhatsThis::enterWhatsThisMode();
679 }
680
681 //////////////////////////////////////////////////////////////////////////////
682 // helpAbout()
683 // -----------
684 // Display the About dialog
685
686 void QBrew::helpAbout()
687 {
688 QString message;
689
690 message = "<center><nobr><big><strong>" + TITLE + tr(" Version ")
691 + VERSION + "</strong></big></nobr></center>";
692 message += "<p align=center><strong>" + tr(DESCRIPTION) + "</strong></p>";
693 message += "<p align=center>" + tr(COPYRIGHT) + ' ' + AUTHOR + "</p>";
694 message += tr("<p align=center><small>Contributions by ")
695 + CONTRIBUTORS + "</small></p>";
696
697 QMessageBox::about(this, tr("About ") + TITLE, message);
698 }
699
700 //////////////////////////////////////////////////////////////////////////////
701 // Settings //
702 //////////////////////////////////////////////////////////////////////////////
703
704 //////////////////////////////////////////////////////////////////////////////
705 // applyGeneralState()
706 // -------------------
707 // Set the general configuration state
708
709 void QBrew::applyGeneralState(const GenConfigState &state)
710 {
711 GenConfigState oldstate = state_.general;
712 state_.general = state;
713
714 // apply immediate state changes
715 if (state.lookfeel != oldstate.lookfeel) {
716 QApplication::setStyle(state.lookfeel);
717 }
718 if ((state.autosave != oldstate.autosave) ||
719 (state.saveinterval != oldstate.saveinterval)) {
720 initAutoSave();
721 }
722 if (state.recentnum < oldstate.recentnum) {
723 while (state_.general.recentfiles.count() > state_.general.recentnum) {
724 state_.general.recentfiles.removeLast();
725 }
726 }
727 statusBar()->showMessage(tr(READY), 2000);
728 }
729
730 //////////////////////////////////////////////////////////////////////////////
731 // applyRecipeState()
732 // ------------------
733 // Set the recipe configuration state
734
735 void QBrew::applyRecipeState(const RecipeConfigState &state)
736 {
737 RecipeConfigState oldstate = state_.recipe;
738 state_.recipe = state;
739
740 // apply state changes
741 if (state.batch != oldstate.batch) {
742 if (state_.calc.units == UNIT_METRIC) {
743 data_->setDefaultSize(Volume(state.batch, Volume::liter));
744 } else if (state_.calc.units == UNIT_US) {
745 data_->setDefaultSize(Volume(state.batch, Volume::gallon));
746 }
747 }
748 if (state.style != oldstate.style) {
749 data_->setDefaultStyle(state.style);
750 }
751 if (state.hoptype != oldstate.hoptype) {
752 data_->setDefaultHopType(state.hoptype);
753 }
754
755 statusBar()->showMessage(tr(READY), 2000);
756 }
757
758 //////////////////////////////////////////////////////////////////////////////
759 // applyCalcState()
760 // ----------------
761 // Set the calc configuration state
762
763 void QBrew::applyCalcState(const CalcConfigState &state)
764 {
765 CalcConfigState oldstate = state_.calc;
766 state_.calc = state;
767
768 // apply state changes
769 if (state.steepyield != oldstate.steepyield) {
770 data_->setSteepYield(state.steepyield);
771 }
772 if (state.efficiency != oldstate.efficiency) {
773 data_->setEfficiency(state.efficiency);
774 }
775 if (state.morey != oldstate.morey) {
776 data_->setMorey(state.morey);
777 }
778 if (state.tinseth != oldstate.tinseth) {
779 data_->setTinseth(state.tinseth);
780 }
781 if (state.units != oldstate.units) {
782 if (state.units == UNIT_METRIC) {
783 data_->setDefaultSize(Volume(state_.recipe.batch,
784 Volume::liter));
785 data_->setDefaultGrainUnit(Weight::kilogram);
786 data_->setDefaultHopUnit(Weight::gram);
787 data_->setDefaultTempUnit(Temperature::celsius);
788 } else if (state.units == UNIT_US) {
789 data_->setDefaultSize(Volume(state_.recipe.batch,
790 Volume::gallon));
791 data_->setDefaultGrainUnit(Weight::pound);
792 data_->setDefaultHopUnit(Weight::ounce);
793 data_->setDefaultTempUnit(Temperature::fahrenheit);
794 }
795 // delete hydrometer tool
796 if (hydrometertool_) {
797 delete hydrometertool_;
798 hydrometertool_ = 0;
799 }
800 }
801
802
803 // recalculate
804 recipe_->recalc();
805 view_->flush();
806
807 statusBar()->showMessage(tr(READY), 2000);
808 }
809
810 //////////////////////////////////////////////////////////////////////////////
811 // saveConfig()
812 // -----------
813 // Save the configuration (when OK pressed in dialog)
814
815 void QBrew::saveConfig()
816 {
817 writeConfig();
818 statusBar()->showMessage(tr("Saved configuration"), 2000);
819 }
820
821 //////////////////////////////////////////////////////////////////////////////
822 // readConfig()
823 // ------------
824 // Read configuration from settings file
825
826 void QBrew::readConfig()
827 {
828 QSettings config;
829 config.beginGroup(QString("/") + PACKAGE);
830
831 // read general config
832 config.beginGroup(CONFGROUP_GENERAL);
833 state_.general.lookfeel =
834 config.value(CONF_GEN_LOOK_FEEL, state_.general.lookfeel).toString();
835 state_.general.showsplash =
836 config.value(CONF_GEN_SHOW_SPLASH, state_.general.showsplash).toBool();
837 state_.general.autosave =
838 config.value(CONF_GEN_AUTOSAVE, state_.general.autosave).toBool();
839 state_.general.saveinterval =
840 config.value(CONF_GEN_SAVEINTERVAL, state_.general.saveinterval).toUInt();
841 state_.general.autobackup =
842 config.value(CONF_GEN_AUTOBACKUP, state_.general.autobackup).toBool();
843 state_.general.loadlast =
844 config.value(CONF_GEN_LOADLAST, state_.general.loadlast).toBool();
845 state_.general.recentnum =
846 config.value(CONF_GEN_RECENTNUM, state_.general.recentnum).toUInt();
847 config.endGroup();
848
849 // read recipe config
850 config.beginGroup(CONFGROUP_RECIPE);
851 state_.recipe.batch =
852 config.value(CONF_RECIPE_BATCH, state_.recipe.batch).toDouble();
853 state_.recipe.style =
854 config.value(CONF_RECIPE_STYLE, state_.recipe.style).toString();
855 // TODO: CONF_RECIPE_HOPFORM is deprecated (0.4.0)
856 if (config.contains(CONF_RECIPE_HOPFORM)) {
857 state_.recipe.hoptype =
858 config.value(CONF_RECIPE_HOPFORM, state_.recipe.hoptype).toString();
859 config.remove(CONF_RECIPE_HOPFORM);
860 } else {
861 state_.recipe.hoptype =
862 config.value(CONF_RECIPE_HOPTYPE, state_.recipe.hoptype).toString();
863 }
864 config.endGroup();
865
866 // read calc config
867 config.beginGroup(CONFGROUP_CALC);
868 state_.calc.steepyield =
869 config.value(CONF_CALC_STEEPYIELD, state_.calc.steepyield).toDouble();
870 state_.calc.efficiency =
871 config.value(CONF_CALC_EFFICIENCY, state_.calc.efficiency).toDouble();
872 state_.calc.morey =
873 config.value(CONF_CALC_MOREY, state_.calc.morey).toBool();
874 state_.calc.tinseth =
875 config.value(CONF_CALC_TINSETH, state_.calc.tinseth).toBool();
876 state_.calc.units =
877 config.value(CONF_CALC_UNITS, state_.calc.units).toString();
878 config.endGroup();
879
880 config.endGroup();
881 }
882
883 //////////////////////////////////////////////////////////////////////////////
884 // writeConfig()
885 // -------------
886 // Write configuration to settings file
887
888 void QBrew::writeConfig()
889 {
890 QSettings config;
891 config.beginGroup(QString("/") + PACKAGE);
892
893 // write general config
894 config.beginGroup(CONFGROUP_GENERAL);
895 config.setValue(CONF_GEN_LOOK_FEEL, state_.general.lookfeel);
896 config.setValue(CONF_GEN_SHOW_SPLASH, state_.general.showsplash);
897 config.setValue(CONF_GEN_AUTOSAVE, state_.general.autosave);
898 config.setValue(CONF_GEN_SAVEINTERVAL, (int)state_.general.saveinterval);
899 config.setValue(CONF_GEN_AUTOBACKUP, state_.general.autobackup);
900 config.setValue(CONF_GEN_LOADLAST, state_.general.loadlast);
901 config.setValue(CONF_GEN_RECENTNUM, (int)state_.general.recentnum);
902 config.endGroup();
903
904 // write recipe config
905 config.beginGroup(CONFGROUP_RECIPE);
906 config.setValue(CONF_RECIPE_BATCH, (double)state_.recipe.batch);
907 config.setValue(CONF_RECIPE_STYLE, state_.recipe.style);
908 config.setValue(CONF_RECIPE_HOPTYPE, state_.recipe.hoptype);
909 config.endGroup();
910
911 // write calc config
912 config.beginGroup(CONFGROUP_CALC);
913 config.setValue(CONF_CALC_STEEPYIELD, (double)state_.calc.steepyield);
914 config.setValue(CONF_CALC_EFFICIENCY, (double)state_.calc.efficiency);
915 config.setValue(CONF_CALC_MOREY, state_.calc.morey);
916 config.setValue(CONF_CALC_TINSETH, state_.calc.tinseth);
917 config.setValue(CONF_CALC_UNITS, state_.calc.units);
918 config.endGroup();
919
920 config.endGroup();
921 }
922
923 //////////////////////////////////////////////////////////////////////////////
924 // restoreState()
925 // ------------
926 // Restore application state
927
928 void QBrew::restoreState()
929 {
930 QSettings config;
931 config.beginGroup(QString("/") + PACKAGE);
932
933 // read window state
934 config.beginGroup(CONFGROUP_WINDOW);
935 state_.window.statusbar = config.value(CONF_WIN_STATUSBAR,
936 state_.window.statusbar).toBool();
937
938 QByteArray mainwindow = config.value(CONF_WIN_MAINWINDOW).toByteArray();
939 QMainWindow::restoreState(mainwindow);
940 resize(config.value(CONF_WIN_SIZE, QSize(600, 400)).toSize());
941 config.endGroup();
942
943 // read general state
944 config.beginGroup(CONFGROUP_GENERAL);
945 state_.general.recentfiles = config.value(CONF_GEN_RECENTFILES).toStringList();
946 while (state_.general.recentfiles.count() > state_.general.recentnum) {
947 state_.general.recentfiles.removeLast();
948 }
949
950 config.endGroup();
951
952 config.endGroup();
953
954 // show or hide statusbar depending on initial setting
955 statusBar()->setVisible(state_.window.statusbar);
956 ui.actiontogglestatusbar->setChecked(state_.window.statusbar);
957 }
958
959 //////////////////////////////////////////////////////////////////////////////
960 // saveSate()
961 // ----------
962 // Save application state
963
964 void QBrew::saveState()
965 {
966 // load config from settings
967 QSettings config;
968 config.beginGroup(QString("/") + PACKAGE);
969
970 // write window state
971 config.beginGroup(CONFGROUP_WINDOW);
972 config.setValue(CONF_WIN_MAINWINDOW, QMainWindow::saveState());
973 config.setValue(CONF_WIN_SIZE, size());
974 config.setValue(CONF_WIN_STATUSBAR, state_.window.statusbar);
975
976 config.endGroup();
977
978 // write general state
979 config.beginGroup(CONFGROUP_GENERAL);
980 config.setValue(CONF_GEN_RECENTFILES, state_.general.recentfiles);
981 config.endGroup();
982
983 config.endGroup();
984 }
985
986 //////////////////////////////////////////////////////////////////////////////
987 // Miscellaneous //
988 //////////////////////////////////////////////////////////////////////////////
989
990 //////////////////////////////////////////////////////////////////////////////
991 // openFile()
992 // ----------
993 // Open the named file
994
995 bool QBrew::openFile(const QString &filename)
996 {
997
998 if (!filename.isEmpty()) {
999 if (recipe_->nativeFormat(filename)) {
1000 if (recipe_->loadRecipe(filename)) {
1001 filename_ = filename;
1002 setFileCaption(filename_);
1003 } else {
1004 // load was unsuccessful
1005 QMessageBox::warning(this, TITLE,
1006 tr("Unable to load the recipe %1")
1007 .arg(QFileInfo(filename_).fileName()));
1008 return false;
1009 }
1010 } else {
1011 bool status = false;
1012 // attempt to import file
1013 if (recipe_->beerXmlFormat(filename)) {
1014 status = recipe_->importBeerXml(filename);
1015 if (status) {
1016 // set filename to the default (forces a saveas)
1017 filename_ = DEFAULT_FILE;
1018 setFileCaption(filename_);
1019 }
1020 }
1021 if (!status) {
1022 // import was unsuccessful
1023 QMessageBox::warning(this, TITLE,
1024 tr("Unable to import the file %1")
1025 .arg(QFileInfo(filename).fileName()));
1026 return false;
1027 }
1028 }
1029
1030 newflag_ = false;
1031 backed_ = false;
1032 addRecent(filename_);
1033 ui.actionfilesave->setEnabled(false);
1034
1035 return true;
1036 }
1037 // empty filename
1038 return false;
1039 }
1040
1041 //////////////////////////////////////////////////////////////////////////////
1042 // saveFile()
1043 // ----------
1044 // Save a file
1045
1046 bool QBrew::saveFile(const QString &filename)
1047 {
1048 bool status = true;
1049
1050 if (!filename.isEmpty()) {
1051 status = recipe_->saveRecipe(filename);
1052
1053 if (status) {
1054 // remove old autosave file if present
1055 if (QFile::exists(autosavename_)) {
1056 QFile::remove(autosavename_);
1057 initAutoSave();
1058 }
1059 }
1060 }
1061
1062 return status;
1063 }
1064
1065 //////////////////////////////////////////////////////////////////////////////
1066 // backupFile()
1067 // ------------
1068 // Backup the current file
1069
1070 bool QBrew::backupFile()
1071 {
1072 if (backed_) return true;
1073
1074 bool status = false;
1075 if (!filename_.isEmpty() && (filename_ != tr(DEFAULT_FILE))) {
1076 if (QFile::exists(filename_ + '~'))
1077 QFile::remove(filename_ + '~');
1078 status = QFile::copy(filename_, filename_ + '~');
1079 if (status) backed_ = true;
1080 }
1081 return status;
1082 }
1083
1084 //////////////////////////////////////////////////////////////////////////////
1085 // recentMenuShow()
1086 // ----------------
1087 // about to show recent file menu
1088
1089 void QBrew::recentMenuShow()
1090 {
1091 ui.menuopenrecent->clear();
1092
1093 QAction *action;
1094 foreach(QString recentfile, state_.general.recentfiles) {
1095 action = new QAction(recentfile, ui.menuopenrecent);
1096 connect(action, SIGNAL(triggered()),
1097 this, SLOT(fileRecent()));
1098 ui.menuopenrecent->addAction(action);
1099 }
1100 }
1101
1102 //////////////////////////////////////////////////////////////////////////////
1103 // addRecent()
1104 // -----------
1105 // Add a file to the recent files list
1106
1107 void QBrew::addRecent(const QString &filename)
1108 {
1109 if (state_.general.recentnum == 0) return;
1110
1111 QFileInfo finfo(filename);
1112 QString filepath = finfo.absoluteFilePath();
1113
1114 if (state_.general.recentfiles.contains(filepath))
1115 state_.general.recentfiles.removeAll(filepath);
1116 if (state_.general.recentfiles.count() >= state_.general.recentnum)
1117 state_.general.recentfiles.removeLast();
1118 state_.general.recentfiles.prepend(filepath);
1119 }
1120
1121 //////////////////////////////////////////////////////////////////////////////
1122 // autoSave()
1123 // ----------
1124 // Time to autosave
1125
1126 void QBrew::autoSave()
1127 {
1128 if (!recipe_->modified()) return;
1129 statusBar()->showMessage(tr("Autosaving recipe..."), 2000);
1130 if ((filename_.isEmpty()) || (filename_ == tr(DEFAULT_FILE))) {
1131 recipe_->saveRecipe(autosavename_);
1132 } else {
1133 if (state_.general.autobackup) backupFile();
1134 recipe_->saveRecipe(filename_);
1135 }
1136 // remove "modified" from caption
1137 setFileCaption(filename_);
1138 }
1139
1140 //////////////////////////////////////////////////////////////////////////////
1141 // setFileCaption()
1142 // ----------------
1143 // Set the window caption from file name
1144
1145 void QBrew::setFileCaption(const QString &filename)
1146 {
1147 setWindowModified(false); // clear modified *
1148
1149 QString shownname;
1150 if (filename.isEmpty()) shownname = tr(DEFAULT_FILE);
1151 else shownname = QFileInfo(filename).fileName();
1152
1153 setWindowTitle(QString("%1 - %2[*]").arg(TITLE.constData()).arg(shownname));
1154 }
1155
1156 //////////////////////////////////////////////////////////////////////////////
1157 // querySave()
1158 // -----------
1159 // Ask the user if they want to save their work before going on
1160
1161 int QBrew::querySave()
1162 {
1163 return QMessageBox::question(this, TITLE + tr(" - Save?"),
1164 tr("<p>Do you wish to save your work first?"),
1165 QMessageBox::Yes,
1166 QMessageBox::No,
1167 QMessageBox::Cancel);
1168 }
1169
1170 //////////////////////////////////////////////////////////////////////////////
1171 // queryOverwrite()
1172 // -----------
1173 // Ask the user if they want to overwrite an existing file
1174
1175 int QBrew::queryOverwrite(const QString filename)
1176 {
1177 return QMessageBox::question(this, TITLE + tr(" - Overwrite?"),
1178 tr("<p>Are you sure you want to "
1179 "overwrite the file \"%1\"")
1180 .arg(filename),
1181 QMessageBox::Yes,
1182 QMessageBox::Cancel);
1183 }
1184
1185 //////////////////////////////////////////////////////////////////////////////
1186 // recipeModified()
1187 // ------------------
1188 // Received when recipe is modified
1189
1190 void QBrew::recipeModified()
1191 {
1192 ui.actionfilesave->setEnabled(true);
1193 setWindowModified(true);
1194 }
1195
1196 //////////////////////////////////////////////////////////////////////////////
1197 // closeEvent()
1198 // -----------
1199 // Catch the close event
1200
1201 void QBrew::closeEvent(QCloseEvent* e)
1202 {
1203 if (!recipe_->modified()) {
1204 e->accept();
1205 } else {
1206 // file needs to be saved, what do we do
1207 switch (querySave()) {
1208 case QMessageBox::Yes:
1209 fileSave();
1210 e->accept();
1211 break;
1212 case QMessageBox::Cancel:
1213 statusBar()->showMessage(tr(READY), 2000);
1214 e->ignore();
1215 break;
1216 case QMessageBox::No:
1217 default:
1218 e->accept();
1219 }
1220 }
1221 }
1222
1223 //////////////////////////////////////////////////////////////////////////////
1224 // eventFilter()
1225 // -----------
1226 // Filter events
1227
1228 bool QBrew::eventFilter(QObject *obj, QEvent *event)
1229 {
1230 // necessary on Mac
1231 if (event->type() == QEvent::FileOpen) {
1232 QFileOpenEvent *openevent = static_cast<QFileOpenEvent *>(event);
1233 fileOpen(openevent->file());
1234 return true;
1235 } else {
1236 // standard event processing
1237 return QObject::eventFilter(obj, event);
1238 }
1239 }
1240
1241 //////////////////////////////////////////////////////////////////////////////
1242 // dataBase()
1243 // ---------
1244 // Figure out the base directory for the data
1245
1246 QString QBrew::dataBase()
1247 {
1248 // TODO: can QDesktopServices help us here?
1249 QString base = qApp->applicationDirPath();
1250
1251 #if defined(Q_WS_X11)
1252 if (QRegExp("qbrew/?$").indexIn(base) != -1) {
1253 // we have our own application directory (it ends in 'qbrew')
1254 base += "/";
1255 } else if (QRegExp("bin/?$").indexIn(base) != -1) {
1256 // we are in the bin dir of a filesystem hiearchy like '/usr/local/bin'
1257 base += "/../share/qbrew/";
1258 } else {
1259 // otherwise punt
1260 base += "/";
1261 }
1262
1263 #elif defined(Q_WS_MAC)
1264 if (QRegExp("Contents/MacOS/?$").indexIn(base) != -1) {
1265 // we're pointing inside an application bundle
1266 base += "/../Resources/";
1267 } else {
1268 // otherwise punt
1269 base += "/";
1270 }
1271
1272 #else // Win32 and others
1273 base += "/";
1274 #endif
1275 return QDir::cleanPath(base) + "/";
1276 }
1277
1278 //////////////////////////////////////////////////////////////////////////////
1279 // docBase()
1280 // ---------
1281 // Figure out the base directory for the documentation
1282
1283 QString QBrew::docBase()
1284 {
1285 QString base = qApp->applicationDirPath();
1286
1287 #if defined(Q_WS_X11)
1288 if (QRegExp("qbrew/?$").indexIn(base) != -1) {
1289 // we have our own application directory (it ends in 'qbrew')
1290 base += "/doc/";
1291 } else if (QRegExp("bin/?$").indexIn(base) != -1) {
1292 // we are in the bin dir of a filesystem hiearchy like '/usr/local/bin'
1293 base += "/../share/doc/qbrew/";
1294 } else {
1295 // otherwise punt'
1296 base += "/doc/";
1297 }
1298
1299 #elif defined(Q_WS_MAC)
1300 if (QRegExp("Contents/MacOS/?$").indexIn(base) != -1) {
1301 // we're pointing inside an application bundle
1302 base += "/../Resources/en.lproj/";
1303 } else if (QFile::exists(base + "/en.lproj/")) {
1304 // some other hierarchy using Mac style l10n
1305 base += "/en.lproj/";
1306 } else {
1307 // otherwise punt
1308 base += "/doc/";
1309 }
1310
1311 #else // Win32 and others
1312 base += "/doc/";
1313 #endif
1314 return QDir::cleanPath(base) + "/";
1315 }