MainFrame.cpp

Go to the documentation of this file.
00001 // -*- c-basic-offset: 4 -*-
00002 
00027 #include <config.h>
00028 #include <exiv2/exif.hpp>
00029 #include <exiv2/image.hpp>
00030 
00031 #include <wx/dir.h>
00032 #include <wx/stdpaths.h>
00033 #include "panoinc_WX.h"
00034 #include "panoinc.h"
00035 
00036 #include "base_wx/platform.h"
00037 #include "base_wx/wxPlatform.h"
00038 
00039 #include "vigra/imageinfo.hxx"
00040 #include "vigra_ext/Correlation.h"
00041 
00042 #include "hugin/config_defaults.h"
00043 #include "hugin/PreferencesDialog.h"
00044 #include "hugin/MainFrame.h"
00045 #include "base_wx/wxPanoCommand.h"
00046 #include "base_wx/CommandHistory.h"
00047 #include "hugin/PanoPanel.h"
00048 #include "hugin/ImagesPanel.h"
00049 #include "hugin/MaskEditorPanel.h"
00050 #include "hugin/OptimizePanel.h"
00051 #include "hugin/OptimizePhotometricPanel.h"
00052 #include "hugin/PreviewFrame.h"
00053 #include "hugin/GLPreviewFrame.h"
00054 #include "hugin/huginApp.h"
00055 #include "hugin/CPEditorPanel.h"
00056 #include "hugin/CPListFrame.h"
00057 #include "hugin/LocalizedFileTipProvider.h"
00058 #include "algorithms/control_points/CleanCP.h"
00059 #include "hugin/PanoOperation.h"
00060 
00061 #include "base_wx/MyProgressDialog.h"
00062 #include "base_wx/RunStitchPanel.h"
00063 #include "base_wx/wxImageCache.h"
00064 #include "base_wx/PTWXDlg.h"
00065 #include "base_wx/MyExternalCmdExecDialog.h"
00066 #include "base_wx/AssistantExecutor.h"
00067 #include "algorithms/optimizer/ImageGraph.h"
00068 
00069 #include "base_wx/huginConfig.h"
00070 #include "hugin/AboutDialog.h"
00071 
00072 #if HUGIN_HSI
00073 #include "PluginItems.h"
00074 #endif
00075 
00076 using namespace HuginBase;
00077 using namespace std;
00078 using namespace hugin_utils;
00079 
00080 #ifdef __MINGW32__
00081 // fixes for mingw compilation...
00082 #undef FindWindow
00083 #endif
00084 
00089 class HuginSplashScreen : public wxFrame
00090 {
00091 public:
00092     HuginSplashScreen() {};
00093     HuginSplashScreen(wxWindow* parent, wxBitmap bitmap) : 
00094         wxFrame(parent, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxFRAME_TOOL_WINDOW | wxFRAME_NO_TASKBAR | wxSTAY_ON_TOP)
00095     {
00096         SetExtraStyle(GetExtraStyle() | wxWS_EX_TRANSIENT);
00097         wxSizer* topSizer=new wxBoxSizer(wxVERTICAL);
00098         wxStaticBitmap* staticBitmap=new wxStaticBitmap(this,wxID_ANY,bitmap);
00099         topSizer->Add(staticBitmap,1,wxEXPAND);
00100         SetSizerAndFit(topSizer);
00101         SetClientSize(bitmap.GetWidth(), bitmap.GetHeight());
00102         CenterOnScreen();
00103         Show(true);
00104         SetFocus();
00105 #if defined(__WXMSW__) || defined(__WXMAC__)
00106         Update();
00107 #elif defined(__WXGTK20__)
00108         //do nothing
00109 #else
00110         wxYieldIfNeeded();
00111 #endif
00112     };
00113     DECLARE_DYNAMIC_CLASS(HuginSplashScreen)
00114     DECLARE_EVENT_TABLE()
00115 };
00116 
00117 IMPLEMENT_DYNAMIC_CLASS(HuginSplashScreen, wxFrame)
00118 BEGIN_EVENT_TABLE(HuginSplashScreen, wxFrame)
00119 END_EVENT_TABLE()
00120 
00122 bool PanoDropTarget::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& filenames)
00123 {
00124     DEBUG_TRACE("OnDropFiles");
00125     MainFrame * mf = MainFrame::Get();
00126     if (!mf) return false;
00127 
00128     if (!m_imageOnly && filenames.GetCount() == 1) {
00129         wxFileName file(filenames[0]);
00130         if (file.GetExt().CmpNoCase(wxT("pto")) == 0 ||
00131             file.GetExt().CmpNoCase(wxT("ptp")) == 0 ||
00132             file.GetExt().CmpNoCase(wxT("pts")) == 0 )
00133         {
00134             // load project
00135             if (mf->CloseProject(true)) {
00136                 mf->LoadProjectFile(file.GetFullPath());
00137                 // remove old images from cache
00138                 ImageCache::getInstance().flush();
00139             }
00140             return true;
00141         }
00142     }
00143 
00144     // try to add as images
00145     std::vector<std::string> filesv;
00146     wxArrayString invalidFiles;
00147     for (unsigned int i=0; i< filenames.GetCount(); i++) {
00148         wxFileName file(filenames[i]);
00149 
00150         if (file.GetExt().CmpNoCase(wxT("jpg")) == 0 ||
00151             file.GetExt().CmpNoCase(wxT("jpeg")) == 0 ||
00152             file.GetExt().CmpNoCase(wxT("tif")) == 0 ||
00153             file.GetExt().CmpNoCase(wxT("tiff")) == 0 ||
00154             file.GetExt().CmpNoCase(wxT("png")) == 0 ||
00155             file.GetExt().CmpNoCase(wxT("bmp")) == 0 ||
00156             file.GetExt().CmpNoCase(wxT("gif")) == 0 ||
00157             file.GetExt().CmpNoCase(wxT("pnm")) == 0 ||
00158             file.GetExt().CmpNoCase(wxT("sun")) == 0 ||
00159             file.GetExt().CmpNoCase(wxT("hdr")) == 0 ||
00160             file.GetExt().CmpNoCase(wxT("viff")) == 0 )
00161         {
00162             if(containsInvalidCharacters(filenames[i]))
00163             {
00164                 invalidFiles.Add(file.GetFullPath());
00165             }
00166             else
00167             {
00168                 filesv.push_back((const char *)filenames[i].mb_str(HUGIN_CONV_FILENAME));
00169             };
00170         }
00171     }
00172     // we got some images to add.
00173     if (filesv.size() > 0)
00174     {
00175         // use a Command to ensure proper undo and updating of GUI parts
00176         wxBusyCursor();
00177         if(pano.getNrOfCtrlPoints()>0)
00178         {
00179             PanoCommand::GlobalCmdHist::getInstance().addCommand(new PanoCommand::wxAddImagesCmd(pano, filesv));
00180         }
00181         else
00182         {
00183             std::vector<PanoCommand::PanoCommand*> cmds;
00184             cmds.push_back(new PanoCommand::wxAddImagesCmd(pano, filesv));
00185             cmds.push_back(new PanoCommand::DistributeImagesCmd(pano));
00186             cmds.push_back(new PanoCommand::CenterPanoCmd(pano));
00187             PanoCommand::GlobalCmdHist::getInstance().addCommand(new PanoCommand::CombinedPanoCommand(pano, cmds));
00188         };
00189 
00190     }
00191     if(invalidFiles.size()>0)
00192     {
00193         ShowFilenameWarning(mf, invalidFiles);
00194     }
00195 
00196     return true;
00197 }
00198 
00199 
00200 
00201 // event table. this frame will recieve mostly global commands.
00202 BEGIN_EVENT_TABLE(MainFrame, wxFrame)
00203     EVT_MENU(XRCID("action_new_project"),  MainFrame::OnNewProject)
00204     EVT_MENU(XRCID("action_load_project"),  MainFrame::OnLoadProject)
00205     EVT_MENU(XRCID("action_save_project"),  MainFrame::OnSaveProject)
00206     EVT_MENU(XRCID("action_save_as_project"),  MainFrame::OnSaveProjectAs)
00207     EVT_MENU(XRCID("action_save_as_ptstitcher"),  MainFrame::OnSavePTStitcherAs)
00208     EVT_MENU(XRCID("action_open_batch_processor"),  MainFrame::OnOpenPTBatcher)
00209     EVT_MENU(XRCID("action_import_project"), MainFrame::OnMergeProject)
00210     EVT_MENU(XRCID("action_apply_template"),  MainFrame::OnApplyTemplate)
00211     EVT_MENU(XRCID("action_exit_hugin"),  MainFrame::OnUserQuit)
00212     EVT_MENU_RANGE(wxID_FILE1, wxID_FILE9, MainFrame::OnMRUFiles)
00213     EVT_MENU(XRCID("action_show_about"),  MainFrame::OnAbout)
00214     EVT_MENU(XRCID("action_show_help"),  MainFrame::OnHelp)
00215     EVT_MENU(XRCID("action_show_tip"),  MainFrame::OnTipOfDay)
00216     EVT_MENU(XRCID("action_show_shortcuts"),  MainFrame::OnKeyboardHelp)
00217     EVT_MENU(XRCID("action_show_faq"),  MainFrame::OnFAQ)
00218     EVT_MENU(XRCID("action_show_donate"),  MainFrame::OnShowDonate)
00219     EVT_MENU(XRCID("action_show_prefs"), MainFrame::OnShowPrefs)
00220     EVT_MENU(XRCID("action_assistant"), MainFrame::OnRunAssistant)
00221     EVT_MENU(XRCID("action_batch_assistant"), MainFrame::OnSendToAssistantQueue)
00222     EVT_MENU(XRCID("action_gui_simple"), MainFrame::OnSetGuiSimple)
00223     EVT_MENU(XRCID("action_gui_advanced"), MainFrame::OnSetGuiAdvanced)
00224     EVT_MENU(XRCID("action_gui_expert"), MainFrame::OnSetGuiExpert)
00225 #ifdef HUGIN_HSI
00226     EVT_MENU(XRCID("action_python_script"), MainFrame::OnPythonScript)
00227 #endif
00228     EVT_MENU(XRCID("ID_EDITUNDO"), MainFrame::OnUndo)
00229     EVT_MENU(XRCID("ID_EDITREDO"), MainFrame::OnRedo)
00230     EVT_MENU(XRCID("ID_SHOW_FULL_SCREEN"), MainFrame::OnFullScreen)
00231     EVT_MENU(XRCID("ID_SHOW_PREVIEW_FRAME"), MainFrame::OnTogglePreviewFrame)
00232     EVT_MENU(XRCID("ID_SHOW_GL_PREVIEW_FRAME"), MainFrame::OnToggleGLPreviewFrame)
00233     EVT_BUTTON(XRCID("ID_SHOW_PREVIEW_FRAME"),MainFrame::OnTogglePreviewFrame)
00234     EVT_BUTTON(XRCID("ID_SHOW_GL_PREVIEW_FRAME"), MainFrame::OnToggleGLPreviewFrame)
00235 
00236     EVT_MENU(XRCID("action_optimize"),  MainFrame::OnOptimize)
00237     EVT_BUTTON(XRCID("action_optimize"),  MainFrame::OnOptimize)
00238     EVT_MENU(XRCID("action_finetune_all_cp"), MainFrame::OnFineTuneAll)
00239 //    EVT_BUTTON(XRCID("action_finetune_all_cp"), MainFrame::OnFineTuneAll)
00240     EVT_MENU(XRCID("action_remove_cp_in_masks"), MainFrame::OnRemoveCPinMasks)
00241 
00242     EVT_MENU(XRCID("ID_CP_TABLE"), MainFrame::OnShowCPFrame)
00243     EVT_BUTTON(XRCID("ID_CP_TABLE"),MainFrame::OnShowCPFrame)
00244 
00245     EVT_MENU(XRCID("ID_SHOW_PANEL_IMAGES"), MainFrame::OnShowPanel)
00246     EVT_MENU(XRCID("ID_SHOW_PANEL_MASK"), MainFrame::OnShowPanel)
00247     EVT_MENU(XRCID("ID_SHOW_PANEL_CP_EDITOR"), MainFrame::OnShowPanel)
00248     EVT_MENU(XRCID("ID_SHOW_PANEL_OPTIMIZER"), MainFrame::OnShowPanel)
00249     EVT_MENU(XRCID("ID_SHOW_PANEL_OPTIMIZER_PHOTOMETRIC"), MainFrame::OnShowPanel)
00250     EVT_MENU(XRCID("ID_SHOW_PANEL_PANORAMA"), MainFrame::OnShowPanel)
00251     EVT_MENU(XRCID("action_stitch"), MainFrame::OnDoStitch)
00252     EVT_MENU(XRCID("action_stitch_userdefined"), MainFrame::OnUserDefinedStitch)
00253     EVT_MENU(XRCID("action_add_images"),  MainFrame::OnAddImages)
00254     EVT_BUTTON(XRCID("action_add_images"),  MainFrame::OnAddImages)
00255     EVT_MENU(XRCID("action_add_time_images"),  MainFrame::OnAddTimeImages)
00256     EVT_BUTTON(XRCID("action_add_time_images"),  MainFrame::OnAddTimeImages)
00257     EVT_CLOSE(  MainFrame::OnExit)
00258     EVT_SIZE(MainFrame::OnSize)
00259 END_EVENT_TABLE()
00260 
00261 // change this variable definition
00262 //wxTextCtrl *itemProjTextMemo;
00263 // image preview
00264 //wxBitmap *p_img = (wxBitmap *) NULL;
00265 //WX_DEFINE_ARRAY()
00266 
00267 MainFrame::MainFrame(wxWindow* parent, Panorama & pano)
00268     : cp_frame(0), pano(pano)
00269 {
00270     preview_frame = 0;
00271     svmModel=NULL;
00272 
00273     bool disableOpenGL=false;
00274 #if wxCHECK_VERSION(2,9,4)
00275     if(wxGetKeyState(WXK_COMMAND))
00276 #else
00277     if(wxGetKeyState(WXK_CONTROL))
00278 #endif
00279     {
00280         wxDialog dlg;
00281         wxXmlResource::Get()->LoadDialog(&dlg, NULL, wxT("disable_opengl_dlg"));
00282         long noOpenGL=wxConfigBase::Get()->Read(wxT("DisableOpenGL"), 0l);
00283         if(noOpenGL==1)
00284         {
00285             XRCCTRL(dlg, "disable_dont_ask_checkbox", wxCheckBox)->SetValue(true);
00286         };
00287         if(dlg.ShowModal()==wxID_OK)
00288         {
00289             if(XRCCTRL(dlg, "disable_dont_ask_checkbox", wxCheckBox)->IsChecked())
00290             {
00291                 wxConfigBase::Get()->Write(wxT("DisableOpenGL"), 1l);
00292             }
00293             else
00294             {
00295                 wxConfigBase::Get()->Write(wxT("DisableOpenGL"), 0l);
00296             };
00297             disableOpenGL=true;
00298         }
00299         else
00300         {
00301             wxConfigBase::Get()->Write(wxT("DisableOpenGL"), 0l);
00302         };
00303     }
00304     else
00305     {
00306         long noOpenGL=wxConfigBase::Get()->Read(wxT("DisableOpenGL"), 0l);
00307         disableOpenGL=(noOpenGL==1);
00308     };
00309 
00310     wxBitmap bitmap;
00311     HuginSplashScreen* splash = 0;
00312     wxYield();
00313 
00314     if (bitmap.LoadFile(huginApp::Get()->GetXRCPath() + wxT("data/splash.png"), wxBITMAP_TYPE_PNG))
00315     {
00316         // embed package version into string.
00317         {
00318             wxMemoryDC dc;
00319             dc.SelectObject(bitmap);
00320 #ifdef __WXMAC__
00321             wxFont font(9, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
00322 #else
00323             wxFont font(8, wxFONTFAMILY_SWISS, wxFONTSTYLE_NORMAL, wxFONTWEIGHT_NORMAL);
00324 #endif
00325             dc.SetFont(font);
00326             dc.SetTextForeground(*wxBLACK);
00327             dc.SetTextBackground(*wxWHITE);
00328             int tw, th;
00329             wxString version;
00330             version.Printf(_("Version %s"), wxString(hugin_utils::GetHuginVersion().c_str(), wxConvLocal).c_str());
00331             dc.GetTextExtent(version, &tw, &th);
00332             // place text on bitmap.
00333             dc.DrawText(version, bitmap.GetWidth() - tw - 3, bitmap.GetHeight() - th - 3);
00334         }
00335 
00336         splash = new HuginSplashScreen(NULL, bitmap);
00337     } else {
00338         wxLogFatalError(_("Fatal installation error\nThe file data/splash.png was not found at:") + huginApp::Get()->GetXRCPath());
00339         abort();
00340     }
00341     //splash->Refresh();
00342     wxYield();
00343 
00344     // save our pointer
00345     m_this = this;
00346 
00347     DEBUG_TRACE("");
00348     // load our children. some children might need special
00349     // initialization. this will be done later.
00350     wxXmlResource::Get()->LoadFrame(this, parent, wxT("main_frame"));
00351     DEBUG_TRACE("");
00352 
00353     // load our menu bar
00354 #ifdef __WXMAC__
00355     wxApp::s_macAboutMenuItemId = XRCID("action_show_about");
00356     wxApp::s_macPreferencesMenuItemId = XRCID("action_show_prefs");
00357     wxApp::s_macExitMenuItemId = XRCID("action_exit_hugin");
00358     wxApp::s_macHelpMenuTitleName = _("&Help");
00359 #endif
00360     wxMenuBar* mainMenu=wxXmlResource::Get()->LoadMenuBar(this, wxT("main_menubar"));
00361     m_menu_file_simple=wxXmlResource::Get()->LoadMenu(wxT("file_menu_simple"));
00362     m_menu_file_advanced=wxXmlResource::Get()->LoadMenu(wxT("file_menu_advanced"));
00363     mainMenu->Insert(0, m_menu_file_simple, _("&File"));
00364     SetMenuBar(mainMenu);
00365 
00366 #ifdef HUGIN_HSI
00367     wxMenuBar* menubar=GetMenuBar();
00368     // the plugin menu will be generated dynamically
00369     wxMenu *pluginMenu=new wxMenu();
00370     // search for all .py files in plugins directory
00371     wxDir dir(GetDataPath()+wxT("plugins"));
00372     if (dir.IsOpened())
00373     {
00374         wxString filename;
00375         bool cont = dir.GetFirst(&filename, wxT("*.py"), wxDIR_FILES | wxDIR_HIDDEN);
00376         PluginItems items;
00377         while (cont)
00378         {
00379             wxFileName file(dir.GetName(), filename);
00380             file.MakeAbsolute();
00381             PluginItem item(file);
00382             if (item.IsAPIValid())
00383             {
00384                 items.push_back(item);
00385             };
00386             cont = dir.GetNext(&filename);
00387         };
00388         items.sort(comparePluginItem);
00389 
00390         int pluginID = wxID_HIGHEST + 2000;
00391         for (PluginItems::const_iterator it = items.begin(); it != items.end(); ++it)
00392         {
00393             PluginItem item = *it;
00394             int categoryID = pluginMenu->FindItem(item.GetCategory());
00395             wxMenu* categoryMenu;
00396             if (categoryID == wxNOT_FOUND)
00397             {
00398                 categoryMenu = new wxMenu();
00399                 pluginMenu->AppendSubMenu(categoryMenu, item.GetCategory());
00400             }
00401             else
00402             {
00403                 categoryMenu = pluginMenu->FindItem(categoryID)->GetSubMenu();
00404             };
00405             categoryMenu->Append(pluginID, item.GetName(), item.GetDescription());
00406             m_plugins[pluginID] = item.GetFilename();
00407             Connect(pluginID, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(MainFrame::OnPlugin));
00408             pluginID++;
00409         };
00410         // show the new menu
00411         if (pluginMenu->GetMenuItemCount() > 0)
00412         {
00413             menubar->Insert(menubar->GetMenuCount() - 2, pluginMenu, _("&Actions"));
00414         };
00415     };
00416 #else
00417     GetMenuBar()->Enable(XRCID("action_python_script"), false);
00418 #endif
00419 
00420     // create tool bar
00421     SetToolBar(wxXmlResource::Get()->LoadToolBar(this, wxT("main_toolbar")));
00422 
00423     // Disable tools by default
00424     enableTools(false);
00425 
00426     // put an "unknown" object in an xrc file and
00427     // take as wxObject (second argument) the return value of wxXmlResource::Get
00428     // finish the images_panel
00429     DEBUG_TRACE("");
00430 
00431     // image_panel
00432     images_panel = XRCCTRL(*this, "images_panel_unknown", ImagesPanel);
00433     assert(images_panel);
00434     images_panel->Init(&pano);
00435     DEBUG_TRACE("");
00436 
00437     m_notebook = XRCCTRL((*this), "controls_notebook", wxNotebook);
00438 //    m_notebook = ((wxNotebook*) ((*this).FindWindow(XRCID("controls_notebook"))));
00439 //    m_notebook = ((wxNotebook*) (FindWindow(XRCID("controls_notebook"))));
00440     DEBUG_ASSERT(m_notebook);
00441 
00442     // the mask panel
00443     mask_panel = XRCCTRL(*this, "mask_panel_unknown", MaskEditorPanel);
00444     assert(mask_panel);
00445     mask_panel->Init(&pano);
00446 
00447     // the pano_panel
00448     DEBUG_TRACE("");
00449     pano_panel = XRCCTRL(*this, "panorama_panel_unknown", PanoPanel);
00450     assert(pano_panel);
00451     pano_panel->Init(&pano);
00452     pano_panel->panoramaChanged (pano); // initialize from pano
00453 
00454     cpe = XRCCTRL(*this, "cp_editor_panel_unknown", CPEditorPanel);
00455     assert(cpe);
00456     cpe->Init(&pano);
00457 
00458     opt_panel = XRCCTRL(*this, "optimizer_panel_unknown", OptimizePanel);
00459     assert(opt_panel);
00460     opt_panel->Init(&pano);
00461     m_show_opt_panel=true;
00462 
00463     opt_photo_panel = XRCCTRL(*this, "optimizer_photometric_panel_unknown", OptimizePhotometricPanel);
00464     assert(opt_photo_panel);
00465     opt_photo_panel->Init(&pano);
00466     m_show_opt_photo_panel=true;
00467 
00468     // generate list of most recently uses files and add it to menu
00469     // needs to be initialized before the fast preview, there we call AddFilesToMenu()
00470     wxConfigBase * config=wxConfigBase::Get();
00471     m_mruFiles.Load(*config);
00472     m_mruFiles.UseMenu(m_menu_file_advanced->FindItem(XRCID("menu_mru"))->GetSubMenu());
00473 
00474     preview_frame = new PreviewFrame(this, pano);
00475     if(disableOpenGL)
00476     {
00477         gl_preview_frame=NULL;
00478         DisableOpenGLTools();
00479         m_mruFiles.AddFilesToMenu();
00480     }
00481     else
00482     {
00483         gl_preview_frame = new GLPreviewFrame(this, pano);
00484     };
00485 
00486     // set the minimize icon
00487 #ifdef __WXMSW__
00488     wxIcon myIcon(GetXRCPath() + wxT("data/hugin.ico"),wxBITMAP_TYPE_ICO);
00489 #else
00490     wxIcon myIcon(GetXRCPath() + wxT("data/hugin.png"),wxBITMAP_TYPE_PNG);
00491 #endif
00492     SetIcon(myIcon);
00493 
00494     // create a new drop handler. wxwindows deletes the automaticall
00495     SetDropTarget(new PanoDropTarget(pano));
00496     DEBUG_TRACE("");
00497 
00498     PanoOperation::GeneratePanoOperationVector();
00499 
00500     // create a status bar
00501     const int fields (2);
00502     CreateStatusBar(fields);
00503     int widths[fields] = {-1, 85};
00504     SetStatusWidths( fields, &widths[0]);
00505     SetStatusText(_("Started"), 0);
00506     wxYield();
00507     DEBUG_TRACE("");
00508 
00509     // observe the panorama
00510     pano.addObserver(this);
00511 
00512     // Set sizing characteristics
00513     //set minumum size
00514 #if defined __WXMAC__ || defined __WXMSW__
00515     // a minimum nice looking size; smaller than this would clutter the layout.
00516     SetSizeHints(900, 675);
00517 #else
00518     // For ASUS eeePc
00519     SetSizeHints(780, 455); //set minumum size
00520 #endif
00521 
00522     // set progress display for image cache.
00523     ImageCache::getInstance().setProgressDisplay(this);
00524 #if defined __WXMSW__
00525     unsigned long long mem = HUGIN_IMGCACHE_UPPERBOUND;
00526     unsigned long mem_low = wxConfigBase::Get()->Read(wxT("/ImageCache/UpperBound"), HUGIN_IMGCACHE_UPPERBOUND);
00527     unsigned long mem_high = wxConfigBase::Get()->Read(wxT("/ImageCache/UpperBoundHigh"), (long) 0);
00528     if (mem_high > 0) {
00529       mem = ((unsigned long long) mem_high << 32) + mem_low;
00530     }
00531     else {
00532       mem = mem_low;
00533     }
00534     ImageCache::getInstance().SetUpperLimit(mem);
00535 #else
00536     ImageCache::getInstance().SetUpperLimit(wxConfigBase::Get()->Read(wxT("/ImageCache/UpperBound"), HUGIN_IMGCACHE_UPPERBOUND));
00537 #endif
00538 
00539     if(splash) {
00540         splash->Close();
00541         delete splash;
00542     }
00543     wxYield();
00544 
00545     // disable automatic Layout() calls, to it by hand
00546     SetAutoLayout(false);
00547 
00548 
00549 #ifdef __WXMSW__
00550     // wxFrame does have a strange background color on Windows, copy color from a child widget
00551     this->SetBackgroundColour(images_panel->GetBackgroundColour());
00552 #endif
00553 
00554 // By using /SUBSYSTEM:CONSOLE /ENTRY:"WinMainCRTStartup" in the linker
00555 // options for the debug build, a console window will be used for stdout
00556 // and stderr. No need to redirect to a file. Better security since we can't
00557 // guarantee that c: exists and writing a file to the root directory is
00558 // never a good idea. release build still uses /SUBSYSTEM:WINDOWS
00559 
00560 #if 0
00561 #ifdef DEBUG
00562 #ifdef __WXMSW__
00563 
00564     freopen("c:\\hugin_stdout.txt", "w", stdout);    // redirect stdout to file
00565     freopen("c:\\hugin_stderr.txt", "w", stderr);    // redirect stderr to file
00566 #endif
00567 #endif
00568 #endif
00569     //reload gui level
00570     long guiLevel=config->Read(wxT("/GuiLevel"),(long)0);
00571     guiLevel=max<long>(0,min<long>(2,guiLevel));
00572     if(guiLevel==GUI_SIMPLE && disableOpenGL)
00573     {
00574         guiLevel=GUI_ADVANCED;
00575     };
00576     SetGuiLevel((GuiLevel)guiLevel);
00577 
00578     DEBUG_TRACE("");
00579 #ifdef __WXGTK__
00580     // set explicit focus to assistant panel for better processing key presses
00581     images_panel->SetFocus();
00582 #endif
00583 }
00584 
00585 MainFrame::~MainFrame()
00586 {
00587     DEBUG_TRACE("dtor");
00588     if(m_guiLevel==GUI_SIMPLE)
00589     {
00590         delete m_menu_file_advanced;
00591     }
00592     else
00593     {
00594         delete m_menu_file_simple;
00595     };
00596     ImageCache::getInstance().setProgressDisplay(NULL);
00597         delete & ImageCache::getInstance();
00598     delete & PanoCommand::GlobalCmdHist::getInstance();
00599 //    delete cpe;
00600 //    delete images_panel;
00601     DEBUG_DEBUG("removing observer");
00602     pano.removeObserver(this);
00603 
00604     // get the global config object
00605     wxConfigBase* config = wxConfigBase::Get();
00606 
00607     StoreFramePosition(this, wxT("MainFrame"));
00608 
00609     //store most recently used files
00610     m_mruFiles.Save(*config);
00611     //store gui level
00612     config->Write(wxT("/GuiLevel"),(long)m_guiLevel);
00613     config->Flush();
00614     if(svmModel!=NULL)
00615     {
00616         celeste::destroySVMmodel(svmModel);
00617     };
00618     PanoOperation::CleanPanoOperationVector();
00619 
00620     DEBUG_TRACE("dtor end");
00621 }
00622 
00623 void MainFrame::panoramaChanged(HuginBase::Panorama &pano)
00624 {
00625     wxToolBar* theToolBar = GetToolBar();
00626     wxMenuBar* theMenuBar = GetMenuBar();
00627     bool can_undo = PanoCommand::GlobalCmdHist::getInstance().canUndo();
00628     theMenuBar->Enable    (XRCID("ID_EDITUNDO"), can_undo);
00629     theToolBar->EnableTool(XRCID("ID_EDITUNDO"), can_undo);
00630     bool can_redo = PanoCommand::GlobalCmdHist::getInstance().canRedo();
00631     theMenuBar->Enable    (XRCID("ID_EDITREDO"), can_redo);
00632     theToolBar->EnableTool(XRCID("ID_EDITREDO"), can_redo);
00633 
00634     //show or hide optimizer and exposure optimizer tab depending on optimizer master switches
00635     if(pano.getOptimizerSwitch()==0 && !m_show_opt_panel)
00636     {
00637         m_notebook->InsertPage(3, opt_panel, _("Optimizer"));
00638         m_show_opt_panel=true;
00639     };
00640     if(pano.getOptimizerSwitch()!=0 && m_show_opt_panel)
00641     {
00642         m_notebook->RemovePage(3);
00643         m_show_opt_panel=false;
00644     };
00645     if(pano.getPhotometricOptimizerSwitch()==0 && !m_show_opt_photo_panel)
00646     {
00647         if(m_show_opt_panel)
00648         {
00649             m_notebook->InsertPage(4, opt_photo_panel, _("Exposure"));
00650         }
00651         else
00652         {
00653             m_notebook->InsertPage(3, opt_photo_panel, _("Exposure"));
00654         }
00655         m_show_opt_photo_panel=true;
00656     };
00657     if(pano.getPhotometricOptimizerSwitch()!=0 && m_show_opt_photo_panel)
00658     {
00659         if(m_show_opt_panel)
00660         {
00661             m_notebook->RemovePage(4);
00662         }
00663         else
00664         {
00665             m_notebook->RemovePage(3);
00666         };
00667         m_show_opt_photo_panel=false;
00668     };
00669     theMenuBar->Enable(XRCID("ID_SHOW_PANEL_OPTIMIZER"), m_show_opt_panel);
00670     theMenuBar->Enable(XRCID("ID_SHOW_PANEL_OPTIMIZER_PHOTOMETRIC"), m_show_opt_photo_panel);
00671 }
00672 
00673 //void MainFrame::panoramaChanged(HuginBase::Panorama &panorama)
00674 void MainFrame::panoramaImagesChanged(HuginBase::Panorama &panorama, const HuginBase::UIntSet & changed)
00675 {
00676     DEBUG_TRACE("");
00677     assert(&pano == &panorama);
00678     if (pano.getNrOfImages() == 0) {
00679           enableTools(false);
00680         } else {
00681           enableTools(true);
00682         }
00683     GetMenuBar()->Enable(XRCID("action_assistant"), pano.getNrOfImages()>=2);
00684     GetMenuBar()->Enable(XRCID("action_batch_assistant"), pano.getNrOfImages()>=2);
00685 }
00686 
00687 void MainFrame::OnUserQuit(wxCommandEvent & e)
00688 {
00689     Close();
00690 }
00691 
00692 bool MainFrame::CloseProject(bool cancelable)
00693 {
00694     if (pano.isDirty()) {
00695         wxMessageDialog message(wxGetActiveWindow(),
00696                                 _("Save changes to the panorama before closing?"),
00697 #ifdef _WINDOWS
00698                                 _("Hugin"),
00699 #else
00700                                 wxT(""),
00701 #endif
00702                                 wxICON_EXCLAMATION | wxYES_NO | (cancelable? (wxCANCEL):0));
00703 #if wxCHECK_VERSION(2, 9, 0)
00704     message.SetExtendedMessage(_("If you close without saving, changes since your last save will be discarded"));
00705     #if defined __WXMAC__ || defined __WXMSW__
00706         // Apple human interface guidelines and Windows user experience interaction guidelines
00707         message.SetYesNoLabels(wxID_SAVE, _("Don't Save"));
00708     #else
00709         // Gnome human interface guidelines:
00710         message.SetYesNoLabels(wxID_SAVE, _("Close without saving"));
00711     #endif
00712 #endif
00713         int answer = message.ShowModal();
00714         switch (answer){
00715             case wxID_YES:
00716             {
00717                 wxCommandEvent dummy;
00718                 OnSaveProject(dummy);
00719                 return !pano.isDirty();
00720             }
00721             case wxID_CANCEL:
00722                 return false;
00723             default: //no save
00724                 return true;
00725         }
00726     }
00727     else return true;
00728 }
00729 
00730 void MainFrame::OnExit(wxCloseEvent & e)
00731 {
00732     DEBUG_TRACE("");
00733     if(m_guiLevel!=GUI_SIMPLE)
00734     {
00735         if(!CloseProject(e.CanVeto()))
00736         {
00737            if (e.CanVeto())
00738            {
00739                 e.Veto();
00740                 return;
00741            }
00742            wxLogError(_("forced close"));
00743         }
00744     }
00745     else
00746     {
00747         if(e.CanVeto())
00748         {
00749             Hide();
00750             e.Veto();
00751             return;
00752         };
00753     };
00754 
00755     if(preview_frame)
00756     {
00757        preview_frame->Close(true);
00758     }
00759 
00760     ImageCache::getInstance().flush();
00761     Destroy();
00762     DEBUG_TRACE("");
00763 }
00764 
00765 void MainFrame::OnSaveProject(wxCommandEvent & e)
00766 {
00767     DEBUG_TRACE("");
00768     try {
00769     wxFileName scriptName = m_filename;
00770     if (m_filename == wxT("")) {
00771         OnSaveProjectAs(e);
00772         scriptName = m_filename;
00773     } else {
00774         // the project file is just a PTOptimizer script...
00775         std::string path = getPathPrefix(std::string(scriptName.GetFullPath().mb_str(HUGIN_CONV_FILENAME)));
00776         DEBUG_DEBUG("stripping " << path << " from image filenames");
00777         std::ofstream script(scriptName.GetFullPath().mb_str(HUGIN_CONV_FILENAME));
00778         script.exceptions ( std::ofstream::eofbit | std::ofstream::failbit | std::ofstream::badbit );
00779         HuginBase::UIntSet all;
00780         if (pano.getNrOfImages() > 0) {
00781            fill_set(all, 0, pano.getNrOfImages()-1);
00782         }
00783         pano.printPanoramaScript(script, pano.getOptimizeVector(), pano.getOptions(), all, false, path);
00784         script.close();
00785 
00786         SetStatusText(wxString::Format(_("saved project %s"), m_filename.c_str()),0);
00787         if(m_guiLevel==GUI_SIMPLE)
00788         {
00789             if(gl_preview_frame)
00790             {
00791                 gl_preview_frame->SetTitle(scriptName.GetName() + wxT(".") + scriptName.GetExt() + wxT(" - ") + _("Hugin - Panorama Stitcher"));
00792             };
00793             SetTitle(scriptName.GetName() + wxT(".") + scriptName.GetExt() + wxT(" - ") + _("Panorama editor"));
00794         }
00795         else
00796         {
00797             SetTitle(scriptName.GetName() + wxT(".") + scriptName.GetExt() + wxT(" - ") + _("Hugin - Panorama Stitcher"));
00798         };
00799 
00800         pano.clearDirty();
00801     }
00802     } catch (std::exception & e) {
00803         wxString err(e.what(), wxConvLocal);
00804             wxMessageBox(wxString::Format(_("Could not save project file \"%s\".\nMaybe the file or the folder is read-only.\n\n(Error code: %s)"),m_filename.c_str(),err.c_str()),_("Error"),wxOK|wxICON_ERROR);
00805     }
00806 }
00807 
00808 void MainFrame::OnSaveProjectAs(wxCommandEvent & e)
00809 {
00810     DEBUG_TRACE("");
00811     wxFileName scriptName;
00812     if (m_filename.IsEmpty())
00813     {
00814         scriptName.Assign(getDefaultProjectName(pano) + wxT(".pto"));
00815     }
00816     else
00817     {
00818         scriptName=m_filename;
00819     };
00820     scriptName.Normalize();
00821     wxFileDialog dlg(wxGetActiveWindow(),
00822                      _("Save project file"),
00823                      scriptName.GetPath(), scriptName.GetFullName(),
00824                      _("Project files (*.pto)|*.pto|All files (*)|*"),
00825                      wxFD_SAVE | wxFD_OVERWRITE_PROMPT, wxDefaultPosition);
00826     if (dlg.ShowModal() == wxID_OK) {
00827         wxConfig::Get()->Write(wxT("/actualPath"), dlg.GetDirectory());  // remember for later
00828         wxString fn = dlg.GetPath();
00829         if (fn.Right(4).CmpNoCase(wxT(".pto"))!=0)
00830         {
00831             fn.Append(wxT(".pto"));
00832             if (wxFile::Exists(fn)) {
00833                 int d = wxMessageBox(wxString::Format(_("File %s exists. Overwrite?"), fn.c_str()),
00834                     _("Save project"), wxYES_NO | wxICON_QUESTION);
00835                 if (d != wxYES) {
00836                     return;
00837                 }
00838             }
00839         }
00840         m_filename = fn;
00841         m_mruFiles.AddFileToHistory(m_filename);
00842         OnSaveProject(e);
00843     }
00844 }
00845 
00846 void MainFrame::OnSavePTStitcherAs(wxCommandEvent & e)
00847 {
00848     DEBUG_TRACE("");
00849     wxString scriptName = m_filename;
00850     if (m_filename == wxT("")) {
00851         scriptName = getDefaultProjectName(pano);
00852     }
00853     wxFileName scriptNameFN(scriptName);
00854     wxString fn = scriptNameFN.GetName() + wxT(".txt");
00855     wxFileDialog dlg(wxGetActiveWindow(),
00856                      _("Save PTmender script file"),
00857                      wxConfigBase::Get()->Read(wxT("/actualPath"),wxT("")), fn,
00858                      _("PTmender files (*.txt)|*.txt"),
00859                      wxFD_SAVE | wxFD_OVERWRITE_PROMPT, wxDefaultPosition);
00860     if (dlg.ShowModal() == wxID_OK) {
00861         wxString fname = dlg.GetPath();
00862         // the project file is just a PTStitcher script...
00863         wxFileName scriptName = fname;
00864         HuginBase::UIntSet all;
00865         if (pano.getNrOfImages() > 0) {
00866             fill_set(all, 0, pano.getNrOfImages()-1);
00867         }
00868         std::ofstream script(scriptName.GetFullPath().mb_str(HUGIN_CONV_FILENAME));
00869         pano.printStitcherScript(script, pano.getOptions(), all);
00870         script.close();
00871     }
00872 
00873 }
00874 
00875 void MainFrame::LoadProjectFile(const wxString & filename)
00876 {
00877     DEBUG_TRACE("");
00878     m_filename = filename;
00879 
00880     // remove old images from cache
00881     // hmm probably not a good idea, if the project is reloaded..
00882     // ImageCache::getInstance().flush();
00883 
00884     SetStatusText( _("Open project:   ") + filename);
00885 
00886     wxFileName fname(filename);
00887     wxString path = fname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);
00888     if (fname.IsOk() && fname.FileExists()) {
00889         wxBusyCursor wait;
00890         deregisterPTWXDlgFcn();
00891         PanoCommand::GlobalCmdHist::getInstance().addCommand(
00892             new PanoCommand::wxLoadPTProjectCmd(pano, (const char *)filename.mb_str(HUGIN_CONV_FILENAME), (const char *)path.mb_str(HUGIN_CONV_FILENAME), true)
00893            );
00894         PanoCommand::GlobalCmdHist::getInstance().clear();
00895         registerPTWXDlgFcn();
00896         DEBUG_DEBUG("project contains " << pano.getNrOfImages() << " after load");
00897         GuiLevel reqGuiLevel=GetMinimumGuiLevel(pano);
00898         if(reqGuiLevel>m_guiLevel)
00899         {
00900             SetGuiLevel(reqGuiLevel);
00901         };
00902         SetStatusText(_("Project opened"));
00903         m_mruFiles.AddFileToHistory(fname.GetFullPath());
00904         if(m_guiLevel==GUI_SIMPLE)
00905         {
00906             if(gl_preview_frame)
00907             {
00908                 gl_preview_frame->SetTitle(fname.GetName() + wxT(".") + fname.GetExt() + wxT(" - ") + _("Hugin - Panorama Stitcher"));
00909             };
00910             SetTitle(fname.GetName() + wxT(".") + fname.GetExt() + wxT(" - ") + _("Panorama editor"));
00911         }
00912         else
00913         {
00914             SetTitle(fname.GetName() + wxT(".") + fname.GetExt() + wxT(" - ") + _("Hugin - Panorama Stitcher"));
00915         };
00916         if (! (fname.GetExt() == wxT("pto"))) {
00917             // do not remember filename if its not a hugin project
00918             // to avoid overwriting the original project with an
00919             // incompatible one
00920             m_filename = wxT("");
00921         }
00922         // get the global config object
00923         wxConfigBase* config = wxConfigBase::Get();
00924         config->Write(wxT("/actualPath"), path);  // remember for later
00925     } else {
00926         SetStatusText( _("Error opening project:   ") + filename);
00927         DEBUG_ERROR("Could not open file " << filename);
00928     }
00929 
00930     // force update of preview window
00931     if ( !(preview_frame->IsIconized() ||(! preview_frame->IsShown()) ) ) {
00932         wxCommandEvent dummy;
00933         preview_frame->OnUpdate(dummy);
00934     }
00935 }
00936 
00937 #ifdef __WXMAC__
00938 void MainFrame::MacOnOpenFile(const wxString & filename)
00939 {
00940     if(!CloseProject(true)) return; //if closing old project is canceled do nothing.
00941 
00942     ImageCache::getInstance().flush();
00943     LoadProjectFile(filename);
00944 }
00945 #endif
00946 
00947 void MainFrame::OnLoadProject(wxCommandEvent & e)
00948 {
00949     DEBUG_TRACE("");
00950 
00951     if(CloseProject(true)) //if closing old project is canceled do nothing.
00952     {
00953         // get the global config object
00954         wxConfigBase* config = wxConfigBase::Get();
00955 
00956         wxString defaultdir = config->Read(wxT("/actualPath"),wxT(""));
00957         wxFileDialog dlg(wxGetActiveWindow(),
00958                          _("Open project file"),
00959                          defaultdir, wxT(""),
00960                          _("Project files (*.pto)|*.pto|All files (*)|*"),
00961                          wxFD_OPEN, wxDefaultPosition);
00962         dlg.SetDirectory(defaultdir);
00963         if (dlg.ShowModal() == wxID_OK)
00964         {
00965             wxString filename = dlg.GetPath();
00966             if(vigra::isImage(filename.mb_str(HUGIN_CONV_FILENAME)))
00967             {
00968                 if(wxMessageBox(wxString::Format(_("File %s is an image file and not a project file.\nThis file can't be open with File, Open.\nDo you want to add this image file to the current project?"),filename.c_str()),
00969 #ifdef __WXMSW__
00970                     _("Hugin"),
00971 #else
00972                     wxT(""),
00973 #endif
00974                     wxYES_NO | wxICON_QUESTION)==wxYES)
00975                 {
00976                     wxArrayString filenameArray;
00977                     filenameArray.Add(filename);
00978                     AddImages(filenameArray);
00979                 };
00980                 return;
00981             }
00982             else
00983             {
00984                 // remove old images from cache
00985                 ImageCache::getInstance().flush();
00986 
00987                 LoadProjectFile(filename);
00988                 return;
00989             };
00990         }
00991     }
00992     // do not close old project
00993     // nothing to open
00994     SetStatusText( _("Open project: cancel"));
00995 }
00996 
00997 void MainFrame::OnNewProject(wxCommandEvent & e)
00998 {
00999     if(!CloseProject(true)) return; //if closing current project is canceled
01000 
01001     m_filename = wxT("");
01002     PanoCommand::GlobalCmdHist::getInstance().addCommand(new PanoCommand::wxNewProjectCmd(pano));
01003     PanoCommand::GlobalCmdHist::getInstance().clear();
01004     // remove old images from cache
01005     ImageCache::getInstance().flush();
01006     if(m_guiLevel==GUI_SIMPLE)
01007     {
01008         if(gl_preview_frame)
01009         {
01010             gl_preview_frame->SetTitle(_("Hugin - Panorama Stitcher"));
01011         };
01012         SetTitle(_("Panorama editor"));
01013     }
01014     else
01015     {
01016         SetTitle(_("Hugin - Panorama Stitcher"));
01017     };
01018 
01019     wxCommandEvent dummy;
01020     preview_frame->OnUpdate(dummy);
01021 }
01022 
01023 void MainFrame::OnAddImages( wxCommandEvent& event )
01024 {
01025     DEBUG_TRACE("");
01026     PanoOperation::AddImageOperation addImage;
01027     UIntSet images;
01028     PanoCommand::PanoCommand* cmd = addImage.GetCommand(wxGetActiveWindow(), pano, images, m_guiLevel);
01029     if(cmd!=NULL)
01030     {
01031         PanoCommand::GlobalCmdHist::getInstance().addCommand(cmd);
01032     }
01033     else
01034     {
01035         // nothing to open
01036         SetStatusText( _("Add Image: cancel"));
01037     }
01038 
01039     DEBUG_TRACE("");
01040 }
01041 
01042 void MainFrame::AddImages(wxArrayString& filenameArray)
01043 {
01044     wxArrayString invalidFiles;
01045     for(unsigned int i=0;i<filenameArray.GetCount(); i++)
01046     {
01047         if(containsInvalidCharacters(filenameArray[i]))
01048         {
01049             invalidFiles.Add(filenameArray[i]);
01050         };
01051     };
01052     if(invalidFiles.size()>0)
01053     {
01054         ShowFilenameWarning(this, invalidFiles);
01055     }
01056     else
01057     {
01058         std::vector<std::string> filesv;
01059         for (unsigned int i=0; i< filenameArray.GetCount(); i++) {
01060             filesv.push_back((const char *)filenameArray[i].mb_str(HUGIN_CONV_FILENAME));
01061         }
01062 
01063         // we got some images to add.
01064         if (filesv.size() > 0) {
01065             // use a Command to ensure proper undo and updating of GUI
01066             // parts
01067             wxBusyCursor();
01068             PanoCommand::GlobalCmdHist::getInstance().addCommand(
01069                 new PanoCommand::wxAddImagesCmd(pano, filesv)
01070                 );
01071         };
01072     };
01073 };
01074 
01075 void MainFrame::OnAddTimeImages( wxCommandEvent& event )
01076 {
01077     PanoOperation::AddImagesSeriesOperation imageSeriesOp;
01078     UIntSet images;
01079     PanoCommand::PanoCommand* cmd = imageSeriesOp.GetCommand(wxGetActiveWindow(), pano, images, m_guiLevel);
01080     if(cmd!=NULL)
01081     {
01082         PanoCommand::GlobalCmdHist::getInstance().addCommand(cmd);
01083     };
01084 };
01085 
01086 void MainFrame::OnShowDonate(wxCommandEvent & e)
01087 {
01088     wxLaunchDefaultBrowser(wxT("http://sourceforge.net/project/project_donations.php?group_id=77506"));
01089 }
01090 
01091 
01092 void MainFrame::OnShowPanel(wxCommandEvent & e)
01093 {
01094     if(e.GetId()==XRCID("ID_SHOW_PANEL_MASK"))
01095         m_notebook->SetSelection(1);
01096     else
01097         if(e.GetId()==XRCID("ID_SHOW_PANEL_CP_EDITOR"))
01098             m_notebook->SetSelection(2);
01099         else
01100             if(e.GetId()==XRCID("ID_SHOW_PANEL_OPTIMIZER"))
01101                 m_notebook->SetSelection(3);
01102             else
01103                 if(e.GetId()==XRCID("ID_SHOW_PANEL_OPTIMIZER_PHOTOMETRIC"))
01104                 {
01105                     if(m_show_opt_panel)
01106                     {
01107                         m_notebook->SetSelection(4);
01108                     }
01109                     else
01110                     {
01111                         m_notebook->SetSelection(3);
01112                     };
01113                 }
01114                 else
01115                     if(e.GetId()==XRCID("ID_SHOW_PANEL_PANORAMA"))
01116                     {
01117                         if(m_show_opt_panel && m_show_opt_photo_panel)
01118                         {
01119                             m_notebook->SetSelection(5);
01120                         }
01121                         else
01122                         {
01123                             if(m_show_opt_panel || m_show_opt_photo_panel)
01124                             {
01125                                 m_notebook->SetSelection(4);
01126                             }
01127                             else
01128                             {
01129                                 m_notebook->SetSelection(3);
01130                             };
01131                         };
01132                     }
01133                     else
01134                         m_notebook->SetSelection(0);
01135 }
01136 
01137 
01138 void MainFrame::OnAbout(wxCommandEvent & e)
01139 {
01140     AboutDialog dlg(wxGetActiveWindow());
01141     dlg.ShowModal();
01142 }
01143 
01144 /*
01145 void MainFrame::OnAbout(wxCommandEvent & e)
01146 {
01147     DEBUG_TRACE("");
01148     wxDialog dlg;
01149         wxString strFile;
01150         wxString langCode;
01151 
01152     wxXmlResource::Get()->LoadDialog(&dlg, this, wxT("about_dlg"));
01153 
01154 #if __WXMAC__ && defined MAC_SELF_CONTAINED_BUNDLE
01155     //rely on the system's locale choice
01156     strFile = MacGetPathToBundledResourceFile(CFSTR("about.htm"));
01157     if(strFile!=wxT("")) XRCCTRL(dlg,"about_html",wxHtmlWindow)->LoadPage(strFile);
01158 #else
01159     //if the language is not default, load custom About file (if exists)
01160     langCode = huginApp::Get()->GetLocale().GetName().Left(2).Lower();
01161     DEBUG_INFO("Lang Code: " << langCode.mb_str(wxConvLocal));
01162     if(langCode != wxString(wxT("en")))
01163     {
01164         strFile = GetXRCPath() + wxT("data/about_") + langCode + wxT(".htm");
01165         if(wxFile::Exists(strFile))
01166         {
01167             DEBUG_TRACE("Using About: " << strFile.mb_str(wxConvLocal));
01168             XRCCTRL(dlg,"about_html",wxHtmlWindow)->LoadPage(strFile);
01169         }
01170     }
01171 #endif
01172     dlg.ShowModal();
01173 }
01174 */
01175 
01176 void MainFrame::OnHelp(wxCommandEvent & e)
01177 {
01178     DisplayHelp(wxT("/Hugin.html"));
01179 }
01180 
01181 void MainFrame::OnKeyboardHelp(wxCommandEvent & e)
01182 {
01183     DisplayHelp(wxT("/Hugin_Keyboard_shortcuts.html"));
01184 }
01185 
01186 void MainFrame::OnFAQ(wxCommandEvent & e)
01187 {
01188     DisplayHelp(wxT("/Hugin_FAQ.html"));
01189 }
01190 
01191 
01192 void MainFrame::DisplayHelp(wxString section)
01193 {
01194     // TODO:
01195     // structure a frame with navigation on the left and content on the right
01196     // always load the same navigation on the left and the section into the frame
01197     // find a way to target always the same window rather than opening new window / tabs in the browser every time
01198     // make it look nicer with some CSS styling
01199 
01200     // section is the HTML document to be displayed, from inside the data folder
01201     if(section==wxT("")){
01202         section = wxT("/Hugin.html");
01203     }
01204 
01205     DEBUG_TRACE("");
01206 
01207 #ifdef __WXMSW__
01208     GetHelpController().DisplaySection(section);
01209 #else
01210 #if defined __WXMAC__ && defined MAC_SELF_CONTAINED_BUNDLE
01211     // On Mac, xrc/data/help_LOCALE should be in the bundle as LOCALE.lproj/help
01212     // which we can rely on the operating sytem to pick the right locale's.
01213     wxString strFile = MacGetPathToBundledResourceFile(CFSTR("help"));
01214     if(strFile!=wxT(""))
01215     {
01216         strFile += section;
01217     } else {
01218         wxLogError(wxString::Format(wxT("Could not find help directory in the bundle"), strFile.c_str()));
01219         return;
01220     }
01221 #else
01222     // find base filename
01223     wxString helpFile = wxT("help_") + huginApp::Get()->GetLocale().GetCanonicalName() + section;
01224     DEBUG_INFO("help file candidate: " << helpFile.mb_str(wxConvLocal));
01225     //if the language is not default, load custom About file (if exists)
01226     wxString strFile = GetXRCPath() + wxT("data/") + helpFile;
01227     if(wxFile::Exists(strFile))
01228     {
01229         DEBUG_TRACE("Using About: " << strFile.mb_str(wxConvLocal));
01230     } else {
01231         strFile = GetXRCPath() + wxT("data/help_en_EN") + section;
01232     }
01233 #endif
01234     if(!wxFile::Exists(strFile))
01235     {
01236         wxLogError(wxString::Format(wxT("Could not open help file: %s"), strFile.c_str()));
01237         return;
01238     }
01239     DEBUG_INFO("help file: " << strFile.mb_str(wxConvLocal));
01240     if(!wxLaunchDefaultBrowser(strFile))
01241     {
01242         wxLogError(_("Can't start system's web browser"));
01243     }
01244 #endif
01245 }
01246 
01247 void MainFrame::OnTipOfDay(wxCommandEvent& WXUNUSED(e))
01248 {
01249     wxString strFile;
01250     bool bShowAtStartup;
01251 // DGSW FIXME - Unreferenced
01252 //      bool bTipsExist = false;
01253     int nValue;
01254 
01255     wxConfigBase * config = wxConfigBase::Get();
01256     nValue = config->Read(wxT("/MainFrame/ShowStartTip"),1l);
01257 
01258     //TODO: tips not localisable
01259     DEBUG_INFO("Tip index: " << nValue);
01260     strFile = GetXRCPath() + wxT("data/tips.txt");  //load default file
01261 
01262     DEBUG_INFO("Reading tips from " << strFile.mb_str(wxConvLocal));
01263     wxTipProvider *tipProvider = new LocalizedFileTipProvider(strFile, nValue);
01264     bShowAtStartup = wxShowTip(wxGetActiveWindow(), tipProvider, (nValue ? true : false));
01265 
01266     //store startup preferences
01267     nValue = (bShowAtStartup ? tipProvider->GetCurrentTip() : 0);
01268     DEBUG_INFO("Writing tip index: " << nValue);
01269     config->Write(wxT("/MainFrame/ShowStartTip"), nValue);
01270     delete tipProvider;
01271 }
01272 
01273 
01274 void MainFrame::OnShowPrefs(wxCommandEvent & e)
01275 {
01276     DEBUG_TRACE("");
01277     PreferencesDialog pref_dlg(wxGetActiveWindow());
01278     pref_dlg.ShowModal();
01279     //update image cache size
01280     wxConfigBase* cfg=wxConfigBase::Get();
01281 #if defined __WXMSW__
01282     unsigned long long mem = HUGIN_IMGCACHE_UPPERBOUND;
01283     unsigned long mem_low = cfg->Read(wxT("/ImageCache/UpperBound"), HUGIN_IMGCACHE_UPPERBOUND);
01284     unsigned long mem_high = cfg->Read(wxT("/ImageCache/UpperBoundHigh"), (long) 0);
01285     if (mem_high > 0)
01286     {
01287       mem = ((unsigned long long) mem_high << 32) + mem_low;
01288     }
01289     else
01290     {
01291       mem = mem_low;
01292     }
01293     ImageCache::getInstance().SetUpperLimit(mem);
01294 #else
01295     ImageCache::getInstance().SetUpperLimit(cfg->Read(wxT("/ImageCache/UpperBound"), HUGIN_IMGCACHE_UPPERBOUND));
01296 #endif
01297     images_panel->ReloadCPDetectorSettings();
01298     if(gl_preview_frame)
01299     {
01300         gl_preview_frame->SetShowProjectionHints(cfg->Read(wxT("/GLPreviewFrame/ShowProjectionHints"),HUGIN_SHOW_PROJECTION_HINTS)!=0);
01301     };
01302 }
01303 
01304 void MainFrame::UpdatePanels( wxCommandEvent& WXUNUSED(event) )
01305 {   // Maybe this can be invoced by the Panorama::Changed() or
01306     // something like this. So no everytime update would be needed.
01307     DEBUG_TRACE("");
01308 }
01309 
01310 void MainFrame::OnTogglePreviewFrame(wxCommandEvent & e)
01311 {
01312     DEBUG_TRACE("");
01313     if (preview_frame->IsIconized()) {
01314         preview_frame->Iconize(false);
01315     }
01316     preview_frame->Show();
01317     preview_frame->Raise();
01318 
01319         // we need to force an update since autoupdate fires
01320         // before the preview frame is shown
01321     wxCommandEvent dummy;
01322         preview_frame->OnUpdate(dummy);
01323 }
01324 
01325 void MainFrame::OnToggleGLPreviewFrame(wxCommandEvent & e)
01326 {
01327     if(gl_preview_frame==NULL)
01328     {
01329         return;
01330     };
01331 #if defined __WXMSW__ || defined __WXMAC__
01332     gl_preview_frame->InitPreviews();
01333 #endif
01334     if (gl_preview_frame->IsIconized()) {
01335         gl_preview_frame->Iconize(false);
01336     }
01337     gl_preview_frame->Show();
01338 #if defined __WXMSW__
01339     // on wxMSW Show() does not send OnShowEvent needed to update the
01340     // visibility state of the fast preview windows
01341     // so explicit calling this event handler
01342     wxShowEvent se;
01343     se.SetShow(true);
01344     gl_preview_frame->OnShowEvent(se);
01345 #elif defined __WXGTK__
01346     gl_preview_frame->LoadOpenGLLayout();
01347 #endif
01348     gl_preview_frame->Raise();
01349 }
01350 
01351 void MainFrame::OnShowCPFrame(wxCommandEvent & e)
01352 {
01353     DEBUG_TRACE("");
01354     if (cp_frame) {
01355         if (cp_frame->IsIconized()) {
01356             cp_frame->Iconize(false);
01357         }
01358         cp_frame->Show();
01359         cp_frame->Raise();
01360     } else {
01361         cp_frame = new CPListFrame(this, pano);
01362         cp_frame->Show();
01363     }
01364 }
01365 
01366 void MainFrame::OnCPListFrameClosed()
01367 {
01368     cp_frame = 0;
01369 }
01370 
01371 void MainFrame::OnOptimize(wxCommandEvent & e)
01372 {
01373     DEBUG_TRACE("");
01374     wxCommandEvent dummy;
01375     opt_panel->OnOptimizeButton(dummy);
01376 }
01377 
01378 void MainFrame::OnPhotometricOptimize(wxCommandEvent & e)
01379 {
01380     wxCommandEvent dummy;
01381     opt_photo_panel->OnOptimizeButton(dummy);
01382 };
01383 
01384 void MainFrame::OnDoStitch(wxCommandEvent & e)
01385 {
01386     DEBUG_TRACE("");
01387     wxCommandEvent cmdEvt(wxEVT_COMMAND_BUTTON_CLICKED,XRCID("pano_button_stitch"));
01388     pano_panel->GetEventHandler()->AddPendingEvent(cmdEvt);
01389 }
01390 
01391 void MainFrame::OnUserDefinedStitch(wxCommandEvent & e)
01392 {
01393     pano_panel->DoUserDefinedStitch();
01394 }
01395 
01396 void MainFrame::OnMergeProject(wxCommandEvent & e)
01397 {
01398     // get the global config object
01399     wxConfigBase* config = wxConfigBase::Get();
01400 
01401     wxString defaultdir = config->Read(wxT("/actualPath"),wxT(""));
01402     wxFileDialog dlg(wxGetActiveWindow(),
01403                      _("Open project file"),
01404                      defaultdir, wxT(""),
01405                      _("Project files (*.pto)|*.pto|All files (*)|*"),
01406                      wxFD_OPEN, wxDefaultPosition);
01407     dlg.SetDirectory(defaultdir);
01408     if (dlg.ShowModal() == wxID_OK)
01409     {
01410         wxString filename = dlg.GetPath();
01411         wxFileName fname(filename);
01412         wxString path = fname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR);
01413         if (fname.IsOk() && fname.FileExists())
01414         {
01415             wxBusyCursor wait;
01416             HuginBase::PanoramaMemento newPano;
01417             std::ifstream in((const char *)fname.GetFullPath().mb_str(HUGIN_CONV_FILENAME));
01418             int ptoversion=0;
01419             if (newPano.loadPTScript(in, ptoversion, (const char *)path.mb_str(HUGIN_CONV_FILENAME)))
01420             {
01421                 Panorama new_pano;
01422                 new_pano.setMemento(newPano);
01423                 PanoCommand::GlobalCmdHist::getInstance().addCommand(
01424                     new PanoCommand::MergePanoCmd(pano, new_pano)
01425                 );
01426                 m_mruFiles.AddFileToHistory(fname.GetFullPath());
01427                 // force update of preview window
01428                 if ( !(preview_frame->IsIconized() ||(! preview_frame->IsShown()) ) )
01429                 {
01430                     wxCommandEvent dummy;
01431                     preview_frame->OnUpdate(dummy);
01432                 };
01433             }
01434             else
01435             {
01436                 wxMessageBox(wxString::Format(_("Could not read project file %s."),fname.GetFullPath().c_str()),_("Error"),wxOK|wxICON_ERROR);
01437             };
01438         };
01439     }
01440 }
01441 
01442 void MainFrame::OnApplyTemplate(wxCommandEvent & e)
01443 {
01444     // get the global config object
01445     wxConfigBase* config = wxConfigBase::Get();
01446 
01447     wxFileDialog dlg(wxGetActiveWindow(),
01448                      _("Choose template project"),
01449                      config->Read(wxT("/templatePath"),wxT("")), wxT(""),
01450                      _("Project files (*.pto)|*.pto|All files (*)|*"),
01451                      wxFD_OPEN, wxDefaultPosition);
01452     dlg.SetDirectory(wxConfigBase::Get()->Read(wxT("/templatePath"),wxT("")));
01453     if (dlg.ShowModal() == wxID_OK) {
01454         wxString filename = dlg.GetPath();
01455         wxConfig::Get()->Write(wxT("/templatePath"), dlg.GetDirectory());  // remember for later
01456 
01457         std::ifstream file((const char *)filename.mb_str(HUGIN_CONV_FILENAME));
01458 
01459         PanoCommand::GlobalCmdHist::getInstance().addCommand(
01460             new PanoCommand::wxApplyTemplateCmd(pano, file));
01461 
01462     }
01463 }
01464 
01465 void MainFrame::OnOpenPTBatcher(wxCommandEvent & e)
01466 {
01467 #if defined __WXMAC__ && defined MAC_SELF_CONTAINED_BUNDLE
01468         // Original patch for OSX by Charlie Reiman dd. 18 June 2011
01469         // Slightly modified by HvdW. Errors in here are mine, not Charlie's. 
01470         FSRef appRef;
01471         FSRef actuallyLaunched;
01472         OSStatus err;
01473         FSRef documentArray[1]; // Don't really need an array if we only have 1 item
01474         LSLaunchFSRefSpec launchSpec;
01475         Boolean  isDir;
01476         
01477         err = LSFindApplicationForInfo(kLSUnknownCreator,
01478                                                                    CFSTR("net.sourceforge.hugin.PTBatcherGUI"),
01479                                                                    NULL,
01480                                                                    &appRef,
01481                                                                    NULL);
01482         if (err != noErr) {
01483                 // error, can't find PTBatcherGUI
01484                 wxMessageBox(wxString::Format(_("External program %s not found in the bundle, reverting to system path"), wxT("open")), _("Error"));
01485                 // Possibly a silly attempt otherwise the previous would have worked as well, but just try it.
01486                 wxExecute(_T("open -b net.sourceforge.hugin.PTBatcherGUI"));
01487         }
01488         else {
01489                 wxExecute(_T("open -b net.sourceforge.hugin.PTBatcherGUI"));
01490         }       
01491 #else
01492     const wxFileName exePath(wxStandardPaths::Get().GetExecutablePath());
01493         wxExecute(exePath.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR) + _T("PTBatcherGUI"));
01494 #endif
01495 }
01496 
01497 void MainFrame::OnFineTuneAll(wxCommandEvent & e)
01498 {
01499     DEBUG_TRACE("");
01500     // fine-tune all points
01501 
01502     HuginBase::CPVector cps = pano.getCtrlPoints();
01503 
01504     // create a map of all control points.
01505     std::set<unsigned int> unoptimized;
01506     for (unsigned int i=0; i < cps.size(); i++) {
01507         // create all control points.
01508         unoptimized.insert(i);
01509     }
01510 
01511     unsigned int nGood=0;
01512     unsigned int nBad=0;
01513 
01514     wxConfigBase *cfg = wxConfigBase::Get();
01515     double corrThresh=HUGIN_FT_CORR_THRESHOLD;
01516     cfg->Read(wxT("/Finetune/CorrThreshold"), &corrThresh, HUGIN_FT_CORR_THRESHOLD);
01517     double curvThresh = HUGIN_FT_CURV_THRESHOLD;
01518     cfg->Read(wxT("/Finetune/CurvThreshold"),&curvThresh, HUGIN_FT_CURV_THRESHOLD);
01519     // load parameters
01520     const long templWidth = cfg->Read(wxT("/Finetune/TemplateSize"), HUGIN_FT_TEMPLATE_SIZE);
01521     const long sWidth = templWidth + cfg->Read(wxT("/Finetune/LocalSearchWidth"), HUGIN_FT_LOCAL_SEARCH_WIDTH);
01522 
01523     {
01524         ProgressReporterDialog progress(unoptimized.size(), _("Fine-tuning all points"), _("Fine-tuning"), wxGetActiveWindow());
01525 
01526     ImageCache & imgCache = ImageCache::getInstance();
01527 
01528     // do not process the control points in random order,
01529     // but walk from image to image, to reduce image reloading
01530     // in low mem situations.
01531     for (unsigned int imgNr = 0 ; imgNr < pano.getNrOfImages(); imgNr++) {
01532         std::set<unsigned int>::iterator it=unoptimized.begin();
01533 
01534         imgCache.softFlush();
01535 
01536         while (it != unoptimized.end()) {
01537             if (cps[*it].image1Nr == imgNr || cps[*it].image2Nr == imgNr) {
01538                 if (!progress.updateDisplayValue())
01539                 {
01540                     return;
01541                 };
01542                 if (cps[*it].mode == HuginBase::ControlPoint::X_Y) {
01543                     // finetune only normal points
01544                     DEBUG_DEBUG("fine tuning point: " << *it);
01545                     wxImage wxSearchImg;
01546                     ImageCache::ImageCacheRGB8Ptr searchImg = imgCache.getImage(
01547                         pano.getImage(cps[*it].image2Nr).getFilename())->get8BitImage();
01548 
01549                     ImageCache::ImageCacheRGB8Ptr templImg = imgCache.getImage(
01550                         pano.getImage(cps[*it].image1Nr).getFilename())->get8BitImage();
01551 
01552                     vigra_ext::CorrelationResult res;
01553                     vigra::Diff2D roundP1(roundi(cps[*it].x1), roundi(cps[*it].y1));
01554                     vigra::Diff2D roundP2(roundi(cps[*it].x2), roundi(cps[*it].y2));
01555 
01556                     res = PointFineTuneProjectionAware(pano.getImage(cps[*it].image1Nr), *templImg, roundP1, templWidth,
01557                         pano.getImage(cps[*it].image2Nr), *searchImg, roundP2, sWidth);
01558 
01559                     // invert curvature. we always assume its a maxima, the curvature there is negative
01560                     // however, we allow the user to specify a positive threshold, so we need to
01561                     // invert it
01562                     res.curv.x = - res.curv.x;
01563                     res.curv.y = - res.curv.y;
01564 
01565                     if (res.maxi < corrThresh || res.curv.x < curvThresh || res.curv.y < curvThresh ||
01566                         res.maxpos.x < 0 || res.maxpos.y < 0 || res.corrPos.x < 0 || res.corrPos.y < 0)
01567                     {
01568                         // Bad correlation result.
01569                         nBad++;
01570                         if (res.maxi >= corrThresh) {
01571                             cps[*it].error = 0;
01572                         }
01573                         cps[*it].error = res.maxi;
01574                         DEBUG_DEBUG("low correlation: " << res.maxi << " curv: " << res.curv);
01575                     } else {
01576                         nGood++;
01577                         // only update if a good correlation was found
01578                         cps[*it].x1 = res.corrPos.x;
01579                         cps[*it].y1 = res.corrPos.y;
01580                         cps[*it].x2 = res.maxpos.x;
01581                         cps[*it].y2 = res.maxpos.y;
01582                         cps[*it].error = res.maxi;
01583                     }
01584                 }
01585                 unsigned int rm = *it;
01586                 ++it;
01587                 unoptimized.erase(rm);
01588             } else {
01589                 ++it;
01590             }
01591         }
01592     }
01593     }
01594     wxString result;
01595     result.Printf(_("%d points fine-tuned, %d points not updated due to low correlation\n\nHint: The errors of the fine-tuned points have been set to the correlation coefficient\nProblematic points can be spotted (just after fine-tune, before optimizing)\nby an error <= %.3f.\nThe error of points without a well defined peak (typically in regions with uniform color)\nwill be set to 0\n\nUse the Control Point list (F3) to see all points of the current project\n"),
01596                   nGood, nBad, corrThresh);
01597     wxMessageBox(result, _("Fine-tune result"), wxOK);
01598     // set newly optimized points
01599     PanoCommand::GlobalCmdHist::getInstance().addCommand(
01600         new PanoCommand::UpdateCPsCmd(pano, cps, false)
01601         );
01602 }
01603 
01604 void MainFrame::OnRemoveCPinMasks(wxCommandEvent & e)
01605 {
01606     if(pano.getCtrlPoints().size()<2)
01607         return;
01608     UIntSet cps=getCPinMasks(pano);
01609     if(cps.size()>0)
01610     {
01611         PanoCommand::GlobalCmdHist::getInstance().addCommand(
01612                     new PanoCommand::RemoveCtrlPointsCmd(pano,cps)
01613                     );
01614         wxMessageBox(wxString::Format(_("Removed %lu control points"), static_cast<unsigned long>(cps.size())),
01615                    _("Removing control points in masks"),wxOK|wxICON_INFORMATION);
01616     };
01617 }
01618 
01619 #ifdef HUGIN_HSI
01620 void MainFrame::OnPythonScript(wxCommandEvent & e)
01621 {
01622     wxString fname;
01623     wxFileDialog dlg(wxGetActiveWindow(),
01624             _("Select python script"),
01625             wxConfigBase::Get()->Read(wxT("/lensPath"),wxT("")), wxT(""),
01626             _("Python script (*.py)|*.py|All files (*.*)|*.*"),
01627             wxFD_OPEN, wxDefaultPosition);
01628     dlg.SetDirectory(wxConfigBase::Get()->Read(wxT("/pythonScriptPath"),wxT("")));
01629 
01630     if (dlg.ShowModal() == wxID_OK)
01631     {
01632         wxString filename = dlg.GetPath();
01633         wxConfig::Get()->Write(wxT("/pythonScriptPath"), dlg.GetDirectory());
01634         std::string scriptfile((const char *)filename.mb_str(HUGIN_CONV_FILENAME));
01635         PanoCommand::GlobalCmdHist::getInstance().addCommand(
01636             new PanoCommand::PythonScriptPanoCmd(pano,scriptfile)
01637             );
01638     }
01639 }
01640 
01641 void MainFrame::OnPlugin(wxCommandEvent & e)
01642 {
01643     wxFileName file=m_plugins[e.GetId()];
01644     if(file.FileExists())
01645     {
01646         std::string scriptfile((const char *)file.GetFullPath().mb_str(HUGIN_CONV_FILENAME));
01647         PanoCommand::GlobalCmdHist::getInstance().addCommand(
01648                                  new PanoCommand::PythonScriptPanoCmd(pano,scriptfile)
01649                                  );
01650     }
01651     else
01652     {
01653         wxMessageBox(wxString::Format(wxT("Python-Script %s not found.\nStopping processing."),file.GetFullPath().c_str()),_("Warning"),wxOK|wxICON_INFORMATION);
01654     };
01655 }
01656 
01657 #endif
01658 
01659 void MainFrame::OnUndo(wxCommandEvent & e)
01660 {
01661     DEBUG_TRACE("OnUndo");
01662     if (PanoCommand::GlobalCmdHist::getInstance().canUndo())
01663     {
01664         PanoCommand::GlobalCmdHist::getInstance().undo();
01665     }
01666     else
01667     {
01668         wxBell();
01669     };
01670 }
01671 
01672 void MainFrame::OnRedo(wxCommandEvent & e)
01673 {
01674     DEBUG_TRACE("OnRedo");
01675     if (PanoCommand::GlobalCmdHist::getInstance().canRedo())
01676     {
01677         PanoCommand::GlobalCmdHist::getInstance().redo();
01678     };
01679 }
01680 
01681 void MainFrame::ShowCtrlPoint(unsigned int cpNr)
01682 {
01683     DEBUG_DEBUG("Showing control point " << cpNr);
01684     m_notebook->SetSelection(2);
01685     cpe->ShowControlPoint(cpNr);
01686 }
01687 
01688 void MainFrame::ShowCtrlPointEditor(unsigned int img1, unsigned int img2)
01689 {
01690     if(!IsShown())
01691     {
01692         Show();
01693         Raise();
01694     };
01695     m_notebook->SetSelection(2);
01696     cpe->setLeftImage(img1);
01697     cpe->setRightImage(img2);
01698 }
01699 
01700 void MainFrame::ShowMaskEditor(size_t imgNr)
01701 {
01702     if(!IsShown())
01703     {
01704         Show();
01705         Raise();
01706     };
01707     m_notebook->SetSelection(1);
01708     mask_panel->setImage(imgNr, true);
01709 };
01710 
01711 void MainFrame::ShowStitcherTab()
01712 {
01714     if(m_show_opt_panel && m_show_opt_photo_panel)
01715     {
01716         m_notebook->SetSelection(5);
01717     }
01718     else
01719     {
01720         if(m_show_opt_panel || m_show_opt_photo_panel)
01721         {
01722             m_notebook->SetSelection(4);
01723         }
01724         else
01725         {
01726             m_notebook->SetSelection(3);
01727         };
01728     };
01729 }
01730 
01732 void MainFrame::updateProgressDisplay()
01733 {
01734     wxString msg;
01735     if (!m_message.empty())
01736     {
01737         msg = wxGetTranslation(wxString(m_message.c_str(), wxConvLocal));
01738         if (!m_filename.empty())
01739         {
01740             msg.Append(wxT(" "));
01741             msg.Append(wxString(ProgressDisplay::m_filename.c_str(), HUGIN_CONV_FILENAME));
01742         };
01743     };
01744     GetStatusBar()->SetStatusText(msg, 0);
01745 
01746 #ifdef __WXMSW__
01747     UpdateWindow(NULL);
01748 #endif
01749 }
01750 
01751 void MainFrame::enableTools(bool option)
01752 {
01753     wxToolBar* theToolBar = GetToolBar();
01754     theToolBar->EnableTool(XRCID("action_optimize"), option);
01755     theToolBar->EnableTool(XRCID("ID_SHOW_PREVIEW_FRAME"), option);
01756     //theToolBar->EnableTool(XRCID("ID_SHOW_GL_PREVIEW_FRAME"), option);
01757     wxMenuBar* theMenuBar = GetMenuBar();
01758     theMenuBar->Enable(XRCID("action_optimize"), option);
01759     theMenuBar->Enable(XRCID("action_finetune_all_cp"), option);
01760     theMenuBar->Enable(XRCID("action_remove_cp_in_masks"), option);
01761     theMenuBar->Enable(XRCID("ID_SHOW_PREVIEW_FRAME"), option);
01762     theMenuBar->Enable(XRCID("action_stitch"), option);
01763     theMenuBar->Enable(XRCID("action_stitch_userdefined"), option);
01764     //theMenuBar->Enable(XRCID("ID_SHOW_GL_PREVIEW_FRAME"), option);
01765 }
01766 
01767 
01768 void MainFrame::OnSize(wxSizeEvent &e)
01769 {
01770     wxSize sz = this->GetSize();
01771     wxSize csz = this->GetClientSize();
01772     wxSize vsz = this->GetVirtualSize();
01773     DEBUG_TRACE(" size:" << sz.x << "," << sz.y <<
01774                 " client: "<< csz.x << "," << csz.y <<
01775                 " virtual: "<< vsz.x << "," << vsz.y);
01776 
01777     Layout();
01778     e.Skip();
01779 }
01780 
01781 CPDetectorSetting& MainFrame::GetDefaultSetting()
01782 {
01783     return images_panel->GetDefaultSetting();
01784 };
01785 
01786 void MainFrame::RunCPGenerator(CPDetectorSetting &setting, const HuginBase::UIntSet& img)
01787 {
01788     images_panel->RunCPGenerator(setting, img);
01789 };
01790 
01791 void MainFrame::RunCPGenerator(const HuginBase::UIntSet& img)
01792 {
01793     images_panel->RunCPGenerator(img);
01794 };
01795 
01796 const wxString MainFrame::GetSelectedCPGenerator()
01797 {
01798     return images_panel->GetSelectedCPGenerator();
01799 };
01800 
01801 const wxString & MainFrame::GetXRCPath()
01802 {
01803      return huginApp::Get()->GetXRCPath();
01804 };
01805 
01806 const wxString & MainFrame::GetDataPath()
01807 {
01808     return wxGetApp().GetDataPath();
01809 };
01810 
01812 MainFrame * MainFrame::Get()
01813 {
01814     if (m_this) {
01815         return m_this;
01816     } else {
01817         DEBUG_FATAL("MainFrame not yet created");
01818         DEBUG_ASSERT(m_this);
01819         return 0;
01820     }
01821 }
01822 
01823 wxString MainFrame::getProjectName()
01824 {
01825     return m_filename;
01826 }
01827 
01828 void MainFrame::OnMRUFiles(wxCommandEvent &e)
01829 {
01830     size_t index = e.GetId() - wxID_FILE1;
01831     wxString f(m_mruFiles.GetHistoryFile(index));
01832     if (!f.empty())
01833     {
01834         wxFileName fn(f);
01835         if(fn.FileExists())
01836             LoadProjectFile(f);
01837         else
01838         {
01839             m_mruFiles.RemoveFileFromHistory(index);
01840             wxMessageBox(wxString::Format(_("File \"%s\" not found.\nMaybe file was renamed, moved or deleted."),f.c_str()),
01841                 _("Error!"),wxOK | wxICON_INFORMATION );
01842         };
01843     };
01844 }
01845 
01846 void MainFrame::OnFullScreen(wxCommandEvent & e)
01847 {
01848     ShowFullScreen(!IsFullScreen(), wxFULLSCREEN_NOBORDER | wxFULLSCREEN_NOCAPTION);
01849 #ifdef __WXGTK__
01850     //workaround a wxGTK bug that also the toolbar is hidden, but not requested to hide
01851     GetToolBar()->Show(true);
01852 #endif
01853 };
01854 
01855 struct celeste::svm_model* MainFrame::GetSVMModel()
01856 {
01857     if(svmModel==NULL)
01858     {
01859         // determine file name of SVM model file
01860         // get XRC path from application
01861         wxString wxstrModelFileName = huginApp::Get()->GetDataPath() + wxT(HUGIN_CELESTE_MODEL);
01862         // convert wxString to string
01863         string strModelFileName(wxstrModelFileName.mb_str(HUGIN_CONV_FILENAME));
01864 
01865         // SVM model file
01866         if (! wxFile::Exists(wxstrModelFileName) ) {
01867             wxMessageBox(wxString::Format(_("Celeste model expected in %s not found, Hugin needs to be properly installed."),wxstrModelFileName.c_str()), _("Fatal Error"));
01868             return NULL;
01869         }
01870         if(!celeste::loadSVMmodel(svmModel,strModelFileName))
01871         {
01872             wxMessageBox(wxString::Format(_("Could not load Celeste model file %s"),wxstrModelFileName.c_str()),_("Error"));
01873             svmModel=NULL;
01874         };
01875     }
01876     return svmModel;
01877 };
01878 
01879 GLPreviewFrame * MainFrame::getGLPreview()
01880 {
01881     return gl_preview_frame;
01882 }
01883 
01884 void MainFrame::SetGuiLevel(GuiLevel newLevel)
01885 {
01886     if(gl_preview_frame==NULL && newLevel==GUI_SIMPLE)
01887     {
01888         SetGuiLevel(GUI_ADVANCED);
01889         return;
01890     };
01891     if(m_guiLevel==GUI_EXPERT && newLevel!=GUI_EXPERT && pano.getOptimizerSwitch()==0)
01892     {
01893         bool needsUpdateOptimizerVar=false;
01894         HuginBase::OptimizeVector optVec = pano.getOptimizeVector();
01895         for(size_t i=0; i<optVec.size(); i++)
01896         {
01897             bool hasTrX=optVec[i].erase("TrX")>0;
01898             bool hasTrY=optVec[i].erase("TrY")>0;
01899             bool hasTrZ=optVec[i].erase("TrZ")>0;
01900             bool hasTpy=optVec[i].erase("Tpy")>0;
01901             bool hasTpp=optVec[i].erase("Tpp")>0;
01902             bool hasg=optVec[i].erase("g")>0;
01903             bool hast=optVec[i].erase("t")>0;
01904             needsUpdateOptimizerVar=needsUpdateOptimizerVar || hasTrX || hasTrY || hasTrZ || hasTpy || hasTpp || hasg || hast;
01905         };
01906         if(needsUpdateOptimizerVar)
01907         {
01908             PanoCommand::GlobalCmdHist::getInstance().addCommand(
01909                 new PanoCommand::UpdateOptimizeVectorCmd(pano, optVec)
01910             );
01911         };
01912     };
01913     if(newLevel==GUI_SIMPLE && pano.getPhotometricOptimizerSwitch()==0)
01914     {
01915         bool needsUpdateOptimizerVar=false;
01916         HuginBase::OptimizeVector optVec = pano.getOptimizeVector();
01917         for(size_t i=0; i<optVec.size(); i++)
01918         {
01919             bool hasVx=optVec[i].erase("Vx")>0;
01920             bool hasVy=optVec[i].erase("Vy")>0;
01921             needsUpdateOptimizerVar=needsUpdateOptimizerVar || hasVx || hasVy;
01922         };
01923         if(needsUpdateOptimizerVar)
01924         {
01925             PanoCommand::GlobalCmdHist::getInstance().addCommand(
01926                 new PanoCommand::UpdateOptimizeVectorCmd(pano, optVec)
01927             );
01928         };
01929     };
01930     m_guiLevel=newLevel;
01931     images_panel->SetGuiLevel(m_guiLevel);
01932     opt_panel->SetGuiLevel(m_guiLevel);
01933     opt_photo_panel->SetGuiLevel(m_guiLevel);
01934     pano_panel->SetGuiLevel(m_guiLevel);
01935     if(gl_preview_frame)
01936     {
01937         gl_preview_frame->SetGuiLevel(m_guiLevel);
01938     };
01939     switch(m_guiLevel)
01940     {
01941         case GUI_SIMPLE:
01942             GetMenuBar()->FindItem(XRCID("action_gui_simple"))->Check();
01943             break;
01944         case GUI_ADVANCED:
01945             GetMenuBar()->FindItem(XRCID("action_gui_advanced"))->Check();
01946             break;
01947         case GUI_EXPERT:
01948             GetMenuBar()->FindItem(XRCID("action_gui_expert"))->Check();
01949             break;
01950     };
01951     if(m_guiLevel==GUI_SIMPLE)
01952     {
01953         if(!gl_preview_frame->IsShown())
01954         {
01955             wxCommandEvent dummy;
01956             OnToggleGLPreviewFrame(dummy);
01957         };
01958         wxGetApp().SetTopWindow(gl_preview_frame);
01959         GetMenuBar()->Remove(0);
01960         GetMenuBar()->Insert(0, m_menu_file_simple, _("&File"));
01961         if(m_filename.IsEmpty())
01962         {
01963             gl_preview_frame->SetTitle(_("Hugin - Panorama Stitcher"));
01964             SetTitle(_("Panorama editor"));
01965         }
01966         else
01967         {
01968             wxFileName scriptName = m_filename;
01969             gl_preview_frame->SetTitle(scriptName.GetName() + wxT(".") + scriptName.GetExt() + wxT(" - ") + _("Hugin - Panorama Stitcher"));
01970             SetTitle(scriptName.GetName() + wxT(".") + scriptName.GetExt() + wxT(" - ") + _("Panorama editor"));
01971         };
01972         Hide();
01973     }
01974     else
01975     {
01976         wxGetApp().SetTopWindow(this);
01977         GetMenuBar()->Remove(0);
01978         GetMenuBar()->Insert(0, m_menu_file_advanced, _("&File"));
01979         if(m_filename.IsEmpty())
01980         {
01981             SetTitle(_("Hugin - Panorama Stitcher"));
01982         }
01983         else
01984         {
01985             wxFileName scriptName = m_filename;
01986             SetTitle(scriptName.GetName() + wxT(".") + scriptName.GetExt() + wxT(" - ") + _("Hugin - Panorama Stitcher"));
01987         };
01988         if(!IsShown())
01989         {
01990             Show();
01991         };
01992     };
01993 };
01994 
01995 void MainFrame::OnSetGuiSimple(wxCommandEvent & e)
01996 {
01997     GuiLevel reqGuiLevel=GetMinimumGuiLevel(pano);
01998     if(reqGuiLevel<=GUI_SIMPLE)
01999     {
02000         SetGuiLevel(GUI_SIMPLE);
02001     }
02002     else
02003     {
02004         if(reqGuiLevel==GUI_ADVANCED)
02005         {
02006             wxMessageBox(_("Can't switch to simple interface. The project is using stacks and/or vignetting center shift.\nThese features are not supported in simple interface."),
02007 #ifdef __WXMSW__
02008                          wxT("Hugin"),
02009 #else
02010                          wxT(""),
02011 #endif
02012                          wxOK | wxICON_INFORMATION);
02013         }
02014         else
02015         {
02016             wxMessageBox(_("Can't switch to simple interface. The project is using translation or shear parameters.\nThese parameters are not supported in simple interface."),
02017 #ifdef __WXMSW__
02018                          wxT("Hugin"),
02019 #else
02020                          wxT(""),
02021 #endif
02022                          wxOK | wxICON_INFORMATION);
02023         }
02024         SetGuiLevel(m_guiLevel);
02025     };
02026 };
02027 
02028 void MainFrame::OnSetGuiAdvanced(wxCommandEvent & e)
02029 {
02030     GuiLevel reqGuiLevel=GetMinimumGuiLevel(pano);
02031     if(reqGuiLevel<=GUI_ADVANCED)
02032     {
02033         SetGuiLevel(GUI_ADVANCED);
02034     }
02035     else
02036     {
02037         wxMessageBox(_("Can't switch to advanced interface. The project is using translation or shear parameters.\nThese parameters are not supported in advanced interface."),
02038 #ifdef __WXMSW__
02039                      wxT("Hugin"),
02040 #else
02041                      wxT(""),
02042 #endif
02043                      wxOK | wxICON_INFORMATION);
02044         SetGuiLevel(GUI_EXPERT);
02045     };
02046 };
02047 
02048 void MainFrame::OnSetGuiExpert(wxCommandEvent & e)
02049 {
02050     SetGuiLevel(GUI_EXPERT);
02051 };
02052 
02053 void MainFrame::DisableOpenGLTools()
02054 {
02055     GetMenuBar()->Enable(XRCID("ID_SHOW_GL_PREVIEW_FRAME"), false);
02056     GetMenuBar()->Enable(XRCID("action_gui_simple"), false);
02057     GetToolBar()->EnableTool(XRCID("ID_SHOW_GL_PREVIEW_FRAME"), false); 
02058 };
02059 
02060 void MainFrame::RunAssistant(wxWindow* mainWin)
02061 {
02062     if (pano.getNrOfImages() < 2)
02063     {
02064         wxMessageBox(_("At least two images are required.\nPlease add more images."),_("Error"), wxOK, mainWin);
02065         return;
02066     }
02067 
02068     //save project into temp directory
02069     wxString tempDir= wxConfig::Get()->Read(wxT("tempDir"),wxT(""));
02070     if(!tempDir.IsEmpty())
02071     {
02072         if(tempDir.Last()!=wxFileName::GetPathSeparator())
02073         {
02074             tempDir.Append(wxFileName::GetPathSeparator());
02075         }
02076     };
02077     wxFileName scriptFileName(wxFileName::CreateTempFileName(tempDir+wxT("ha")));
02078     std::ofstream script(scriptFileName.GetFullPath().mb_str(HUGIN_CONV_FILENAME));
02079     script.exceptions ( std::ofstream::eofbit | std::ofstream::failbit | std::ofstream::badbit );
02080     HuginBase::UIntSet all;
02081     fill_set(all, 0, pano.getNrOfImages()-1);
02082     pano.printPanoramaScript(script, pano.getOptimizeVector(), pano.getOptions(), all, false);
02083     script.close();
02084 
02085     // get assistant queue
02086     const wxFileName exePath(wxStandardPaths::Get().GetExecutablePath());
02087     HuginQueue::CommandQueue* commands = HuginQueue::GetAssistantCommandQueue(pano, exePath.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR), scriptFileName.GetFullPath());
02088     //execute queue
02089     int ret = MyExecuteCommandQueue(commands, mainWin, _("Running assistant"));
02090 
02091     //read back panofile
02092     PanoCommand::GlobalCmdHist::getInstance().addCommand(new PanoCommand::wxLoadPTProjectCmd(pano,
02093         (const char *)scriptFileName.GetFullPath().mb_str(HUGIN_CONV_FILENAME), 
02094         (const char *)scriptFileName.GetPath(wxPATH_NATIVE | wxPATH_GET_SEPARATOR).mb_str(HUGIN_CONV_FILENAME), 
02095         ret==0, false));
02096 
02097     //delete temporary files
02098     wxRemoveFile(scriptFileName.GetFullPath());
02099     //if return value is non-zero, an error occured in the assistant
02100     if(ret!=0)
02101     {
02102         //check for unconnected images
02103         HuginBase::CPGraph graph;
02104         HuginBase::createCPGraph(pano, graph);
02105         HuginBase::CPComponents comps;
02106         const size_t n = HuginBase::findCPComponents(graph, comps);
02107         if(n > 1)
02108         {
02109             // switch to images panel.
02110             unsigned i1 = *(comps[0].rbegin());
02111             unsigned i2 = *(comps[1].begin());
02112             ShowCtrlPointEditor( i1, i2);
02113             // display message box with 
02114             wxMessageBox(wxString::Format(_("Warning %d unconnected image groups found:"), n) + Components2Str(comps) + wxT("\n")
02115                 + _("Please create control points between unconnected images using the Control Points tab.\n\nAfter adding the points, press the \"Align\" button again"),_("Error"), wxOK , mainWin);
02116             return;
02117         };
02118         wxMessageBox(_("The assistant did not complete successfully. Please check the resulting project file."),
02119                      _("Warning"),wxOK | wxICON_INFORMATION, mainWin); 
02120     };
02121 };
02122 
02123 void MainFrame::OnRunAssistant(wxCommandEvent & e)
02124 {
02125     RunAssistant(this);
02126 };
02127 
02128 void MainFrame::OnSendToAssistantQueue(wxCommandEvent &e)
02129 {
02130     wxCommandEvent dummy;
02131     OnSaveProject(dummy);
02132     wxString projectFile = getProjectName();
02133     if(wxFileName::FileExists(projectFile))
02134     {
02135 #if defined __WXMAC__ && defined MAC_SELF_CONTAINED_BUNDLE
02136         // Original patch for OSX by Charlie Reiman dd. 18 June 2011
02137         // Slightly modified by HvdW. Errors in here are mine, not Charlie's. 
02138         FSRef appRef;
02139         FSRef actuallyLaunched;
02140         OSStatus err;
02141         FSRef documentArray[1]; // Don't really need an array if we only have 1 item
02142         LSLaunchFSRefSpec launchSpec;
02143         Boolean  isDir;
02144 
02145         err = LSFindApplicationForInfo(kLSUnknownCreator,
02146                                        CFSTR("net.sourceforge.hugin.PTBatcherGUI"),
02147                                        NULL,
02148                                        &appRef,
02149                                        NULL);
02150         if (err != noErr)
02151         {
02152             // error, can't find PTBatcherGUI
02153             wxMessageBox(wxString::Format(_("External program %s not found in the bundle, reverting to system path"), wxT("open")), _("Error"));
02154             // Possibly a silly attempt otherwise the previous would have worked as well, but just try it.
02155             wxExecute(_T("open -b net.sourceforge.hugin.PTBatcherGUI ")+wxQuoteFilename(projectFile));
02156             return;
02157         }
02158 
02159         wxCharBuffer projectFilebuffer=projectFile.ToUTF8();
02160         // Point to document
02161         err = FSPathMakeRef((unsigned char*) projectFilebuffer.data(), &documentArray[0], &isDir);
02162         if (err != noErr || isDir)
02163         {
02164             // Something went wrong.
02165             wxMessageBox(wxString::Format(_("Project file not found"), wxT("open")), _("Error"));
02166             return;
02167         }
02168         launchSpec.appRef = &appRef;
02169         launchSpec.numDocs = sizeof(documentArray)/sizeof(documentArray[0]);
02170         launchSpec.itemRefs = documentArray;
02171         launchSpec.passThruParams = NULL;
02172         launchSpec.launchFlags = kLSLaunchDontAddToRecents + kLSLaunchDontSwitch;
02173         launchSpec.asyncRefCon = NULL;
02174 
02175         err = LSOpenFromRefSpec(&launchSpec, &actuallyLaunched);
02176         if (err != noErr && err != kLSLaunchInProgressErr)
02177         {  
02178             // Should be ok if it's in progress... I think. 
02179             // Launch failed.
02180             wxMessageBox(wxString::Format(_("Can't launch PTBatcherGui"), wxT("open")), _("Error"));
02181             return;
02182         }
02183 
02184         // Should verify that actuallyLaunched and appRef are the same.
02185         if (FSCompareFSRefs(&appRef, &actuallyLaunched) != noErr)
02186         {
02187             // error, lauched the wrong thing.
02188             wxMessageBox(wxString::Format(_("Launched incorrect programme"), wxT("open")), _("Error"));
02189             return;
02190         }
02191 #else
02192         const wxFileName exePath(wxStandardPaths::Get().GetExecutablePath());
02193         wxExecute(exePath.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR) + wxT("PTBatcherGUI -a ")+wxQuoteFilename(projectFile));
02194 #endif
02195     }
02196 };
02197 
02198 wxString MainFrame::GetCurrentOptimizerString()
02199 {
02200     return images_panel->GetCurrentOptimizerString();
02201 };
02202 
02203 MainFrame * MainFrame::m_this = 0;

Generated on 29 Jul 2015 for Hugintrunk by  doxygen 1.4.7