rework restore_windows for layout
[goodguy/cinelerra.git] / cinelerra-5.1 / cinelerra / mwindow.C
1 /*
2  * CINELERRA
3  * Copyright (C) 1997-2014 Adam Williams <broadcast at earthling dot net>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  */
20
21 #include "aboutprefs.h"
22 #include "asset.h"
23 #include "assets.h"
24 #include "atrack.h"
25 #include "audioalsa.h"
26 #include "autos.h"
27 #include "awindowgui.h"
28 #include "awindow.h"
29 #include "batchrender.h"
30 #include "bcdisplayinfo.h"
31 #include "bcprogressbox.h"
32 #include "bcsignals.h"
33 #include "bctimer.h"
34 #include "bctrace.h"
35 #include "bdcreate.h"
36 #include "brender.h"
37 #include "cache.h"
38 #include "channel.h"
39 #include "channeldb.h"
40 #include "channelinfo.h"
41 #include "clip.h"
42 #include "clipedls.h"
43 #include "bccmodels.h"
44 #include "commercials.h"
45 #include "confirmsave.h"
46 #include "cplayback.h"
47 #include "ctimebar.h"
48 #include "cwindowgui.h"
49 #include "cwindow.h"
50 #include "cwindowtool.h"
51 #include "bchash.h"
52 #include "devicedvbinput.inc"
53 #include "dvdcreate.h"
54 #include "editpanel.h"
55 #include "edl.h"
56 #include "edlsession.h"
57 #include "errorbox.h"
58 #include "fileformat.h"
59 #include "file.h"
60 #include "filesystem.h"
61 #include "filexml.h"
62 #include "floatautos.h"
63 #include "framecache.h"
64 #include "gwindow.h"
65 #include "gwindowgui.h"
66 #include "keyframegui.h"
67 #include "indexfile.h"
68 #include "intautos.h"
69 #include "interlacemodes.h"
70 #include "language.h"
71 #include "levelwindowgui.h"
72 #include "levelwindow.h"
73 #include "loadfile.inc"
74 #include "localsession.h"
75 #include "maincursor.h"
76 #include "mainerror.h"
77 #include "mainindexes.h"
78 #include "mainmenu.h"
79 #include "mainprogress.h"
80 #include "mainsession.h"
81 #include "mainundo.h"
82 #include "mbuttons.h"
83 #include "mutex.h"
84 #include "mwindowgui.h"
85 #include "mwindow.h"
86 #include "new.h"
87 #include "panautos.h"
88 #include "patchbay.h"
89 #include "playback3d.h"
90 #include "playbackengine.h"
91 #include "plugin.h"
92 #include "pluginserver.h"
93 #include "pluginset.h"
94 #include "preferences.h"
95 #include "proxy.h"
96 #include "record.h"
97 #include "recordmonitor.h"
98 #include "recordlabel.h"
99 #include "removefile.h"
100 #include "render.h"
101 #include "resourcethread.h"
102 #include "savefile.inc"
103 #include "samplescroll.h"
104 #include "sha1.h"
105 #include "sighandler.h"
106 #include "splashgui.h"
107 #include "statusbar.h"
108 #include "theme.h"
109 #include "threadloader.h"
110 #include "timebar.h"
111 #include "timelinepane.h"
112 #include "tipwindow.h"
113 #include "trackcanvas.h"
114 #include "track.h"
115 #include "tracking.h"
116 #include "trackscroll.h"
117 #include "tracks.h"
118 #include "transition.h"
119 #include "transportque.h"
120 #include "vframe.h"
121 #include "vtrack.h"
122 #include "versioninfo.h"
123 #include "videodevice.inc"
124 #include "videowindow.h"
125 #include "vplayback.h"
126 #include "vwindowgui.h"
127 #include "vwindow.h"
128 #include "wavecache.h"
129 #include "wwindow.h"
130 #include "zoombar.h"
131 #include "zwindow.h"
132 #include "zwindowgui.h"
133 #include "exportedl.h"
134
135 #include "defaultformats.h"
136 #include "ntsczones.h"
137
138 #include <stdint.h>
139 #include <stdlib.h>
140 #include <unistd.h>
141 #include <fcntl.h>
142 #include <string.h>
143 #include <sys/types.h>
144 #include <sys/stat.h>
145 #include <sys/time.h>
146 #include <sys/mman.h>
147 #include <sys/file.h>
148 #include <limits.h>
149 #include <errno.h>
150
151
152 extern "C"
153 {
154
155
156
157
158 // Hack for libdv to remove glib dependancy
159
160 // void
161 // g_log (const char    *log_domain,
162 //        int  log_level,
163 //        const char    *format,
164 //        ...)
165 // {
166 // }
167 //
168 // void
169 // g_logv (const char    *log_domain,
170 //        int  log_level,
171 //        const char    *format,
172 //        ...)
173 // {
174 // }
175 //
176
177 }
178
179
180 extern long cin_timezone;
181
182 ArrayList<PluginServer*>* MWindow::plugindb = 0;
183 Commercials* MWindow::commercials = 0;
184
185
186 MWindow::MWindow()
187  : Thread(1, 0, 0)
188 {
189         run_lock = new Mutex("MWindow::run_lock");
190         plugin_gui_lock = new Mutex("MWindow::plugin_gui_lock");
191         dead_plugin_lock = new Mutex("MWindow::dead_plugin_lock");
192         vwindows_lock = new Mutex("MWindow::vwindows_lock");
193         zwindows_lock = new Mutex("MWindow::zwindows_lock");
194         brender_lock = new Mutex("MWindow::brender_lock");
195         keyframe_gui_lock = new Mutex("MWindow::keyframe_gui_lock");
196
197         playback_3d = 0;
198         splash_window = 0;
199         undo = 0;
200         defaults = 0;
201         assets = 0;
202         //commercials = 0;
203         commercial_active = 0;
204         audio_cache = 0;
205         video_cache = 0;
206         frame_cache = 0;
207         wave_cache = 0;
208         preferences = 0;
209         session = 0;
210         theme = 0;
211         mainindexes = 0;
212         mainprogress = 0;
213         brender = 0;
214         brender_active = 0;
215         strcpy(cin_lang,"en");
216         channeldb_buz =  new ChannelDB;
217         channeldb_v4l2jpeg =  new ChannelDB;
218         plugin_guis = 0;
219         dead_plugins = 0;
220         keyframe_threads = 0;
221         create_bd = 0;
222         create_dvd = 0;
223         batch_render = 0;
224         render = 0;
225         edl = 0;
226         gui = 0;
227         cwindow = 0;
228         awindow = 0;
229         gwindow = 0;
230         twindow = 0;
231         wwindow = 0;
232         lwindow = 0;
233         sighandler = 0;
234         restart_status = 0;
235         screens = 1;
236         in_destructor = 0;
237         speed_edl = 0;
238         proxy_beep = 0;
239 }
240
241
242 // Need to delete brender temporary here.
243 MWindow::~MWindow()
244 {
245         run_lock->lock("MWindow::~MWindow");
246         in_destructor = 1;
247 //printf("MWindow::~MWindow %d\n", __LINE__);
248         gui->remote_control->deactivate();
249         gui->record->stop();
250 #ifdef HAVE_DVB
251         gui->channel_info->stop();
252 #endif
253         delete proxy_beep;
254         delete create_bd;       create_bd = 0;
255         delete create_dvd;      create_dvd = 0;
256         delete batch_render;    batch_render = 0;
257         delete render;          render = 0;
258         commit_commercial();
259         if( commercials && !commercials->remove_user() ) commercials = 0;
260         close_mixers();
261         if( speed_edl ) { speed_edl->remove_user();  speed_edl = 0; }
262 // Save defaults for open plugins
263         plugin_gui_lock->lock("MWindow::~MWindow");
264         for(int i = 0; i < plugin_guis->size(); i++) {
265                 plugin_guis->get(i)->hide_gui();
266                 delete_plugin(plugin_guis->get(i));
267         }
268         plugin_gui_lock->unlock();
269         hide_keyframe_guis();
270         clean_indexes();
271         save_defaults();
272 // Give up and go to a movie
273 //  cant run valgrind if this is used
274
275         gui->del_keyboard_listener(
276                 (int (BC_WindowBase::*)(BC_WindowBase *))
277                 &MWindowGUI::keyboard_listener);
278 #if 0
279 // release the hounds
280         if( awindow && awindow->gui ) awindow->gui->close(0);
281         if( cwindow && cwindow->gui ) cwindow->gui->close(0);
282         if( lwindow && lwindow->gui ) lwindow->gui->close(0);
283         if( gwindow && gwindow->gui ) gwindow->gui->close(0);
284         if( twindow && twindow->is_running() ) twindow->close_window();
285         if( wwindow && wwindow->is_running() ) wwindow->close_window();
286         vwindows.remove_all_objects();
287         zwindows.remove_all_objects();
288         gui->close(0);
289         if( awindow ) awindow->join();
290         if( cwindow ) cwindow->join();
291         if( lwindow ) lwindow->join();
292         if( twindow ) twindow->join();
293         if( wwindow ) wwindow->join();
294         if( gwindow ) gwindow->join();
295         join();
296 #else
297 // one at a time, or nouveau chokes
298 #define close_gui(win) if( win ) { \
299   if( win->gui ) win->gui->close(0); \
300   win->join(); }
301         close_gui(awindow);
302         close_gui(cwindow);
303         close_gui(lwindow);
304         close_gui(gwindow);
305         close_gui(twindow);
306         close_gui(wwindow);
307         vwindows.remove_all_objects();
308         zwindows.remove_all_objects();
309         gui->close(0);
310         join();
311 #endif
312         reset_caches();
313         dead_plugins->remove_all_objects();
314 // must delete theme before destroying plugindb
315 //  theme destructor will be deleted by delete_plugins
316         delete theme;           theme = 0;
317         delete_plugins();
318         finit_error();
319         keyframe_threads->remove_all_objects();
320         colormodels.remove_all_objects();
321         delete awindow;         awindow = 0;
322         delete lwindow;         lwindow = 0;
323         delete twindow;         twindow = 0;
324         delete wwindow;         wwindow = 0;
325         delete gwindow;         gwindow = 0;
326         delete cwindow;         cwindow = 0;
327         delete gui;             gui = 0;
328         delete mainindexes;     mainindexes = 0;
329         delete mainprogress;    mainprogress = 0;
330         delete audio_cache;     audio_cache = 0;  // delete the cache after the assets
331         delete video_cache;     video_cache = 0;  // delete the cache after the assets
332         delete frame_cache;     frame_cache = 0;
333         delete wave_cache;      wave_cache = 0;
334         delete plugin_guis;     plugin_guis = 0;
335         delete dead_plugins;    dead_plugins = 0;
336         delete keyframe_threads;  keyframe_threads = 0;
337         delete undo;            undo = 0;
338         delete preferences;     preferences = 0;
339         delete exportedl;       exportedl = 0;
340         delete session;         session = 0;
341         delete defaults;        defaults = 0;
342         delete assets;          assets = 0;
343         delete splash_window;   splash_window = 0;
344         if( !edl->Garbage::remove_user() ) edl = 0;
345         delete channeldb_buz;
346         delete channeldb_v4l2jpeg;
347 // This must be last thread to exit
348         delete playback_3d;     playback_3d = 0;
349         delete dead_plugin_lock;
350         delete plugin_gui_lock;
351         delete vwindows_lock;
352         delete zwindows_lock;
353         delete brender_lock;
354         delete keyframe_gui_lock;
355         colormodels.remove_all_objects();
356         interlace_project_modes.remove_all_objects();
357         interlace_asset_modes.remove_all_objects();
358         interlace_asset_fixmethods.remove_all_objects();
359         sighandler->terminate();
360         delete sighandler;
361         delete run_lock;
362 }
363
364
365 void MWindow::quit()
366 {
367         gui->set_done(0);
368 }
369
370 void MWindow::init_error()
371 {
372         MainError::init_error(this);
373 }
374
375 void MWindow::finit_error()
376 {
377         MainError::finit_error();
378 }
379
380 void MWindow::create_defaults_path(char *string, const char *config_file)
381 {
382 // set the .bcast path
383         FileSystem fs;
384
385         sprintf(string, "%s/", File::get_config_path());
386         fs.complete_path(string);
387         if(!fs.is_dir(string))
388                 fs.create_dir(string);
389
390 // load the defaults
391         strcat(string, config_file);
392 }
393 const char *MWindow::default_std()
394 {
395         char buf[BCTEXTLEN], *p = 0;
396
397         int fd = open(TIMEZONE_NAME, O_RDONLY);
398         if( fd >= 0 ) {
399                 int l = read(fd, buf, sizeof(buf)-1);
400                 close(fd);
401                 if( l > 0 ) {
402                         if( buf[l-1] == '\n' ) --l;
403                         buf[l] = 0;
404                         p = buf;
405                 }
406         }
407         if( !p ) {
408                 int l = readlink(LOCALTIME_LINK, buf, sizeof(buf)-1);
409                 if( l > 0 ) {
410                         buf[l] = 0;
411                         if( !(p=strstr(buf, ZONEINFO_STR)) != 0 ) return "PAL";
412                         p += strlen(ZONEINFO_STR);
413                 }
414         }
415
416         if( p ) {
417                 for( int i=0; ntsc_zones[i]; ++i ) {
418                         if( !strcmp(ntsc_zones[i], p) )
419                                 return "NTSC";
420                 }
421         }
422
423         p = getenv("TZ");
424         if( p ) {
425                 for( int i=0; ntsc_zones[i]; ++i ) {
426                         if( !strcmp(ntsc_zones[i], p) )
427                                 return "NTSC";
428                 }
429         }
430
431 // cin_timezone: Seconds west of UTC.  240sec/deg
432         double tz_deg =  -cin_timezone / 240.;
433 // from Honolulu = -10, to New York = -5, 15deg/hr   lat -150..-75
434         return tz_deg >= -10*15 && tz_deg <= -5*15 ? "NTSC" : "PAL";
435 }
436
437 void MWindow::fill_preset_defaults(const char *preset, EDLSession *session)
438 {
439         struct formatpresets *fpr;
440
441         for(fpr = &format_presets[0]; fpr->name; fpr++)
442         {
443                 if(strcmp(_(fpr->name), preset) == 0)
444                 {
445                         session->audio_channels = fpr->audio_channels;
446                         session->audio_tracks = fpr->audio_tracks;
447                         session->sample_rate = fpr->sample_rate;
448                         session->video_channels = fpr->video_channels;
449                         session->video_tracks = fpr->video_tracks;
450                         session->frame_rate = fpr->frame_rate;
451                         session->output_w = fpr->output_w;
452                         session->output_h = fpr->output_h;
453                         session->aspect_w = fpr->aspect_w;
454                         session->aspect_h = fpr->aspect_h;
455                         session->interlace_mode = fpr->interlace_mode;
456                         session->color_model = fpr->color_model;
457                         return;
458                 }
459         }
460 }
461
462 const char *MWindow::get_preset_name(int index)
463 {
464         if(index < 0 || index >= (int)MAX_NUM_PRESETS)
465                 return "Error";
466         return _(format_presets[index].name);
467 }
468
469
470 void MWindow::init_defaults(BC_Hash* &defaults, char *config_path)
471 {
472         char path[BCTEXTLEN];
473 // Use user supplied path
474         if(config_path[0])
475                 strcpy(path, config_path);
476         else
477                 create_defaults_path(path, CONFIG_FILE);
478
479         delete defaults;
480         defaults = new BC_Hash(path);
481         defaults->load();
482 }
483
484
485 void MWindow::check_language()
486 {
487         char curr_lang[BCTEXTLEN]; curr_lang[0] = 0;
488         const char *env_lang = getenv("LANGUAGE");
489         if( !env_lang ) env_lang = getenv("LC_ALL");
490         if( !env_lang ) env_lang = getenv("LANG");
491         if( !env_lang ) {
492                 snprintf(curr_lang, sizeof(curr_lang), "%s_%s-%s",
493                         BC_Resources::language, BC_Resources::region, BC_Resources::encoding);
494                 env_lang = curr_lang;
495         }
496         char last_lang[BCTEXTLEN]; last_lang[0] = 0;
497         defaults->get("LAST_LANG",last_lang);
498         if( strcmp(env_lang,last_lang)) {
499                 printf("lang changed from '%s' to '%s'\n", last_lang, env_lang);
500                 defaults->update("LAST_LANG",env_lang);
501                 char plugin_path[BCTEXTLEN];
502                 create_defaults_path(plugin_path, PLUGIN_FILE);
503                 ::remove(plugin_path);
504                 char ladspa_path[BCTEXTLEN];
505                 create_defaults_path(ladspa_path, LADSPA_FILE);
506                 ::remove(ladspa_path);
507                 defaults->save();
508         }
509         if( strlen(env_lang) > 1 &&
510             ( env_lang[2] == 0 || env_lang[2] == '_'  || env_lang[2] == '.' ) ) {
511                 cin_lang[0] = env_lang[0];  cin_lang[1] = env_lang[1];  cin_lang[2] = 0;
512         }
513         else
514                 strcpy(cin_lang, "en");
515 }
516
517 void MWindow::get_plugin_path(char *path, const char *plug_dir, const char *fs_path)
518 {
519         char *base_path = FileSystem::basepath(fs_path), *bp = base_path;
520         if( plug_dir ) {
521                 const char *dp = plug_dir;
522                 while( *bp && *dp && *bp == *dp ) { ++bp; ++dp; }
523                 bp = !*dp && *bp == '/' ? bp+1 : base_path;
524         }
525         strcpy(path, bp);
526         delete [] base_path;
527 }
528
529 int MWindow::load_plugin_index(MWindow *mwindow, FILE *fp, const char *plugin_dir)
530 {
531         if( !fp ) return -1;
532 // load index
533         fseek(fp, 0, SEEK_SET);
534         int ret = 0;
535         char index_line[BCTEXTLEN];
536         int index_version = -1, len = strlen(plugin_dir);
537         if( !fgets(index_line, BCTEXTLEN, fp) ||
538             sscanf(index_line, "%d", &index_version) != 1 ||
539             index_version != PLUGIN_FILE_VERSION ||
540             !fgets(index_line, BCTEXTLEN, fp) ||
541             (int)strlen(index_line)-1 != len || index_line[len] != '\n' ||
542             strncmp(index_line, plugin_dir, len) != 0 ) ret = 1;
543
544         ArrayList<PluginServer*> plugins;
545         while( !ret && !feof(fp) && fgets(index_line, BCTEXTLEN, fp) ) {
546                 if( index_line[0] == ';' ) continue;
547                 if( index_line[0] == '#' ) continue;
548                 int type = PLUGIN_TYPE_UNKNOWN;
549                 char path[BCTEXTLEN], title[BCTEXTLEN];
550                 int64_t mtime = 0;
551                 if( PluginServer::scan_table(index_line, type, path, title, mtime) ) {
552                         ret = 1; continue;
553                 }
554                 PluginServer *server = 0;
555                 switch( type ) {
556                 case PLUGIN_TYPE_BUILTIN:
557                 case PLUGIN_TYPE_EXECUTABLE:
558                 case PLUGIN_TYPE_LADSPA: {
559                         char plugin_path[BCTEXTLEN];  struct stat st;
560                         sprintf(plugin_path, "%s/%s", plugin_dir, path);
561                         if( stat(plugin_path, &st) || st.st_mtime != mtime ) {
562                                 ret = 1; continue;
563                         }
564                         server = new PluginServer(mwindow, plugin_path, type);
565                         break; }
566                 case PLUGIN_TYPE_FFMPEG: {
567                         server = new_ffmpeg_server(mwindow, path);
568                         break; }
569                 case PLUGIN_TYPE_LV2: {
570                         server = new_lv2_server(mwindow, path);
571                         break; }
572                 }
573                 if( !server ) continue;
574                 plugins.append(server);
575 // Create plugin server from index entry
576                 server->set_title(title);
577                 if( server->read_table(index_line) ) {
578                         ret = 1;  continue;
579                 }
580         }
581
582         if( !ret )
583                 ret = check_plugin_index(plugins, plugin_dir, ".");
584
585         if( !ret )
586                 add_plugins(plugins);
587         else
588                 plugins.remove_all_objects();
589
590         return ret;
591 }
592
593 int MWindow::check_plugin_index(ArrayList<PluginServer*> &plugins,
594         const char *plug_dir, const char *plug_path)
595 {
596         char plugin_path[BCTEXTLEN];
597         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
598         FileSystem fs;
599         fs.set_filter( "[*.plugin][*.so]" );
600         if( fs.update(plugin_path) )
601                 return 1;
602
603         for( int i=0; i<fs.dir_list.total; ++i ) {
604                 char fs_path[BCTEXTLEN];
605                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
606                 if( fs.is_dir(fs_path) ) {
607                         get_plugin_path(plugin_path, plug_dir, fs_path);
608                         if( check_plugin_index(plugins, plug_dir, plugin_path) )
609                                 return 1;
610                 }
611                 else if( !plugin_exists(fs_path, plugins) )
612                         return 1;
613         }
614         return 0;
615 }
616
617
618 int MWindow::init_plugins(MWindow *mwindow, Preferences *preferences)
619 {
620         if( !plugindb )
621                 plugindb = new ArrayList<PluginServer*>;
622         init_ffmpeg();
623         char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
624         create_defaults_path(index_path, PLUGIN_FILE);
625         char *plugin_dir = FileSystem::basepath(preferences->plugin_dir);
626         strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
627         FILE *fp = fopen(index_path,"a+");
628         if( !fp ) {
629                 fprintf(stderr,_("MWindow::init_plugins: "
630                         "can't open plugin index: %s\n"), index_path);
631                 return -1;
632         }
633         int fd = fileno(fp), ret = -1;
634         if( !flock(fd, LOCK_EX) ) {
635                 fseek(fp, 0, SEEK_SET);
636                 ret = load_plugin_index(mwindow, fp, plugin_path);
637         }
638         if( ret > 0 ) {
639                 ftruncate(fd, 0);
640                 fseek(fp, 0, SEEK_SET);
641                 printf("init plugin index: %s\n", plugin_path);
642                 fprintf(fp, "%d\n", PLUGIN_FILE_VERSION);
643                 fprintf(fp, "%s\n", plugin_path);
644                 init_plugin_index(mwindow, preferences, fp, plugin_path);
645                 init_ffmpeg_index(mwindow, preferences, fp);
646                 init_lv2_index(mwindow, preferences, fp);
647                 fseek(fp, 0, SEEK_SET);
648                 ret = load_plugin_index(mwindow, fp, plugin_path);
649         }
650         if( ret ) {
651                 fprintf(stderr,_("MWindow::init_plugins: "
652                         "can't %s plugin index: %s\n"),
653                         ret>0 ? _("create") : _("lock"), index_path);
654         }
655         fclose(fp);
656         return ret;
657 }
658
659 int MWindow::init_ladspa_plugins(MWindow *mwindow, Preferences *preferences)
660 {
661         char *path = getenv("LADSPA_PATH");
662         char ladspa_path[BCTEXTLEN];
663         if( !path ) {
664                 strncpy(ladspa_path, File::get_ladspa_path(), sizeof(ladspa_path));
665                 path = ladspa_path;
666         }
667         for( int len=0; *path; path+=len ) {
668                 char *cp = strchr(path,':');
669                 len = !cp ? strlen(path) : cp-path;
670                 char index_path[BCTEXTLEN], plugin_path[BCTEXTLEN];
671                 memcpy(plugin_path, path, len);  plugin_path[len] = 0;
672                 if( cp ) ++len;
673                 char *plugin_dir = FileSystem::basepath(plugin_path);
674                 strcpy(plugin_path, plugin_dir);  delete [] plugin_dir;
675                 create_defaults_path(index_path, LADSPA_FILE);
676                 cp = index_path + strlen(index_path);
677                 for( char *bp=plugin_path; *bp!=0; ++bp )
678                         *cp++ = *bp=='/' ? '_' : *bp;
679                 *cp = 0;
680                 FILE *fp = fopen(index_path,"a+");
681                 if( !fp ) {
682                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
683                                 "can't open ladspa plugin index: %s\n"), index_path);
684                         continue;
685                 }
686                 int fd = fileno(fp), ret = -1;
687                 if( !flock(fd, LOCK_EX) ) {
688                         fseek(fp, 0, SEEK_SET);
689                         ret = load_plugin_index(mwindow, fp, plugin_path);
690                 }
691                 if( ret > 0 ) {
692                         ftruncate(fd, 0);
693                         fseek(fp, 0, SEEK_SET);
694                         init_ladspa_index(mwindow, preferences, fp, plugin_path);
695                         fseek(fp, 0, SEEK_SET);
696                         ret = load_plugin_index(mwindow, fp, plugin_path);
697                 }
698                 if( ret ) {
699                         fprintf(stderr,_("MWindow::init_ladspa_plugins: "
700                                 "can't %s ladspa plugin index: %s\n"),
701                                 ret>0 ? _("create") : _("lock"), index_path);
702                 }
703                 fclose(fp);
704         }
705         return 1;
706 }
707
708 void MWindow::init_plugin_index(MWindow *mwindow, Preferences *preferences,
709         FILE *fp, const char *plugin_dir)
710 {
711         int idx = PLUGIN_IDS;
712         if( plugindb ) {
713                 for( int i=0; i<plugindb->size(); ++i ) {
714                         PluginServer *server = plugindb->get(i);
715                         if( server->dir_idx >= idx )
716                                 idx = server->dir_idx+1;
717                 }
718         }
719         scan_plugin_index(mwindow, preferences, fp, plugin_dir, ".", idx);
720 }
721
722 void MWindow::scan_plugin_index(MWindow *mwindow, Preferences *preferences, FILE *fp,
723         const char *plug_dir, const char *plug_path, int &idx)
724 {
725         char plugin_path[BCTEXTLEN];
726         sprintf(plugin_path, "%s/%s", plug_dir, plug_path);
727         FileSystem fs;
728         fs.set_filter( "[*.plugin][*.so]" );
729         int result = fs.update(plugin_path);
730         if( result || !fs.dir_list.total ) return;
731         int vis_id = idx++;
732
733         for( int i=0; i<fs.dir_list.total; ++i ) {
734                 char fs_path[BCTEXTLEN], path[BCTEXTLEN];
735                 get_plugin_path(fs_path, 0, fs.dir_list[i]->path);
736                 get_plugin_path(path, plug_dir, fs_path);
737                 if( fs.is_dir(fs_path) ) {
738                         scan_plugin_index(mwindow, preferences, fp, plug_dir, path, idx);
739                         continue;
740                 }
741                 if( plugin_exists(path) ) continue;
742                 struct stat st;
743                 if( stat(fs_path, &st) ) continue;
744                 int64_t mtime = st.st_mtime;
745                 PluginServer server(mwindow, fs_path, PLUGIN_TYPE_UNKNOWN);
746                 result = server.open_plugin(1, preferences, 0, 0);
747                 if( !result ) {
748                         server.write_table(fp, path, vis_id, mtime);
749                         server.close_plugin();
750                 }
751                 else if( result == PLUGINSERVER_IS_LAD ) {
752                         int lad_index = 0;
753                         for(;;) {
754                                 PluginServer ladspa(mwindow, fs_path, PLUGIN_TYPE_LADSPA);
755                                 ladspa.set_lad_index(lad_index++);
756                                 result = ladspa.open_plugin(1, preferences, 0, 0);
757                                 if( result ) break;
758                                 ladspa.write_table(fp, path, PLUGIN_LADSPA_ID, mtime);
759                                 ladspa.close_plugin();
760                         }
761                 }
762         }
763 }
764
765 void MWindow::add_plugins(ArrayList<PluginServer*> &plugins)
766 {
767         for( int i=0; i<plugins.size(); ++i )
768                 plugindb->append(plugins[i]);
769         plugins.remove_all();
770 }
771
772 void MWindow::init_plugin_tips(ArrayList<PluginServer*> &plugins, const char *lang)
773 {
774         const char *dat_path = File::get_cindat_path();
775         char msg_path[BCTEXTLEN];
776         FILE *fp = 0;
777         if( BC_Resources::language[0] ) {
778                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.%s",
779                         dat_path, lang);
780                 fp = fopen(msg_path, "r");
781         }
782         if( !fp ) {
783                 snprintf(msg_path, sizeof(msg_path), "%s/info/plugins.txt",
784                         dat_path);
785                 fp = fopen(msg_path, "r");
786         }
787         if( !fp ) return;
788         char text[BCTEXTLEN];
789         char *tp = text, *ep = tp + sizeof(text)-1;
790         char title[BCTEXTLEN];
791         title[0] = 0;
792         int no = 0;
793         for(;;) {
794                 ++no;  int done = 1;
795                 char line[BCTEXTLEN], *cp = line;
796                 if( fgets(line,sizeof(line)-1,fp) ) {
797                         if( *cp == '#' ) continue;
798                         done = *cp == ' ' || *cp == '\t' ? 0 : -1;
799                 }
800                 if( done ) {
801                         if( tp > text && *--tp == '\n' ) *tp = 0;
802                         if( title[0] ) {
803                                 int idx = plugins.size();
804                                 while( --idx>=0 && strcmp(plugins[idx]->title, title) );
805                                 if( idx >= 0 ) {
806                                         delete [] plugins[idx]->tip;
807                                         plugins[idx]->tip = cstrdup(text);
808                                 }
809                                 title[0] = 0;
810                         }
811                         if( done > 0 ) break;
812                         tp = text;  *tp = 0;
813                         char *dp = strchr(cp, ':');
814                         if( !dp ) {
815                                 printf("plugin tips: error on line %d\n", no);
816                                 continue;
817                         }
818                         char *bp = title;
819                         while( cp < dp ) *bp++ = *cp++;
820                         *bp = 0;
821                         ++cp;
822                 }
823
824                 while( *cp == ' ' || *cp == '\t' ) ++cp;
825                 for( ; tp<ep && (*tp=*cp)!=0; ++tp,++cp );
826         }
827         fclose(fp);
828 }
829
830 void MWindow::delete_plugins()
831 {
832         plugindb->remove_all_objects();
833         delete plugindb;
834         plugindb = 0;
835 }
836
837 void MWindow::search_plugindb(int do_audio,
838                 int do_video,
839                 int is_realtime,
840                 int is_transition,
841                 int is_theme,
842                 ArrayList<PluginServer*> &results)
843 {
844 // Get plugins
845         for(int i = 0; i < MWindow::plugindb->total; i++)
846         {
847                 PluginServer *current = MWindow::plugindb->get(i);
848
849                 if(current->audio == do_audio &&
850                         current->video == do_video &&
851                         (current->realtime == is_realtime || is_realtime < 0) &&
852                         current->transition == is_transition &&
853                         current->theme == is_theme)
854                         results.append(current);
855         }
856
857 // Alphabetize list by title
858         int done = 0;
859         while(!done)
860         {
861                 done = 1;
862
863                 for(int i = 0; i < results.total - 1; i++)
864                 {
865                         PluginServer *value1 = results[i];
866                         PluginServer *value2 = results[i + 1];
867                         if(strcmp(_(value1->title), _(value2->title)) > 0)
868                         {
869                                 done = 0;
870                                 results[i] = value2;
871                                 results[i + 1] = value1;
872                         }
873                 }
874         }
875 }
876
877 PluginServer* MWindow::scan_plugindb(char *title,
878                 int data_type)
879 {
880 //      if(data_type < 0)
881 //      {
882 //              printf("MWindow::scan_plugindb data_type < 0\n");
883 //              return 0;
884 //      }
885
886         for(int i = 0; i < plugindb->total; i++)
887         {
888                 PluginServer *server = plugindb->get(i);
889                 if(server->title &&
890                         !strcasecmp(server->title, title) &&
891                         (data_type < 0 ||
892                                 (data_type == TRACK_AUDIO && server->audio) ||
893                                 (data_type == TRACK_VIDEO && server->video)))
894                         return plugindb->get(i);
895         }
896         return 0;
897 }
898
899 // repair session files with xlated plugin titles
900 void MWindow::fix_plugin_title(char *title)
901 {
902         for(int i = 0; i < plugindb->total; i++) {
903                 PluginServer *server = plugindb->get(i);
904                 if( !server->title ) continue;
905                 const char *server_title = server->title;
906                 if( !bstrcasecmp(title, _(server_title)) ) {
907                         strcpy(title, server_title);
908                         return;
909                 }
910         }
911 }
912
913 int MWindow::plugin_exists(const char *plugin_path, ArrayList<PluginServer*> &plugins)
914 {
915         for( int i=0; i<plugins.size(); ++i )
916                 if( !strcmp(plugin_path, plugins[i]->get_path()) ) return 1;
917         return 0;
918 }
919
920 int MWindow::plugin_exists(char *plugin_path)
921 {
922         return !plugindb ? 0 : plugin_exists(plugin_path, *plugindb);
923 }
924
925 void MWindow::remove_plugin_index()
926 {
927         char index_path[BCTEXTLEN];
928         MWindow::create_defaults_path(index_path, PLUGIN_FILE);
929         ::remove(index_path);
930 }
931
932 void MWindow::init_preferences()
933 {
934         preferences = new Preferences;
935         preferences->load_defaults(defaults);
936         const char *lv2_path = getenv("LV2_PATH");
937         if( lv2_path && strcmp(lv2_path, preferences->lv2_path) ) {
938                 strncpy(preferences->lv2_path, lv2_path, sizeof(preferences->lv2_path));
939                 remove_plugin_index();
940         }
941         else if( !lv2_path && preferences->lv2_path[0] ) {
942                 File::setenv_path("LV2_PATH",preferences->lv2_path, 0);
943         }
944         session = new MainSession(this);
945         session->load_defaults(defaults);
946         // set x11_host, screens, window_config
947         screens = session->set_default_x11_host();
948         BC_Signals::set_trap_hook(trap_hook, this);
949         BC_Signals::set_catch_segv(preferences->trap_sigsegv);
950         BC_Signals::set_catch_intr(preferences->trap_sigintr);
951         if( preferences->trap_sigsegv || preferences->trap_sigintr ) {
952                 BC_Trace::enable_locks();
953         }
954         else {
955                 BC_Trace::disable_locks();
956         }
957         BC_WindowBase::get_resources()->popupmenu_btnup = preferences->popupmenu_btnup;
958         BC_WindowBase::get_resources()->textbox_focus_policy = preferences->textbox_focus_policy;
959         BC_WindowBase::get_resources()->grab_input_focus = preferences->grab_input_focus;
960         YUV::yuv.yuv_set_colors(preferences->yuv_color_space, preferences->yuv_color_range);
961 }
962
963 void MWindow::clean_indexes()
964 {
965         FileSystem fs;
966         int total_excess;
967         long oldest = 0;
968         int oldest_item = -1;
969         int result;
970         char string[BCTEXTLEN];
971         char string2[BCTEXTLEN];
972
973 // Delete extra indexes
974         fs.set_filter("*.idx");
975         fs.complete_path(preferences->index_directory);
976         fs.update(preferences->index_directory);
977 //printf("MWindow::clean_indexes 1 %d\n", fs.dir_list.total);
978
979 // Eliminate directories
980         result = 1;
981         while(result)
982         {
983                 result = 0;
984                 for(int i = 0; i < fs.dir_list.total && !result; i++)
985                 {
986                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
987                         if(fs.is_dir(string))
988                         {
989                                 delete fs.dir_list[i];
990                                 fs.dir_list.remove_number(i);
991                                 result = 1;
992                         }
993                 }
994         }
995         total_excess = fs.dir_list.total - preferences->index_count;
996
997 //printf("MWindow::clean_indexes 2 %d\n", fs.dir_list.total);
998         while(total_excess > 0)
999         {
1000 // Get oldest
1001                 for(int i = 0; i < fs.dir_list.total; i++)
1002                 {
1003                         fs.join_names(string, preferences->index_directory, fs.dir_list[i]->name);
1004
1005                         if(i == 0 || fs.get_date(string) <= oldest)
1006                         {
1007                                 oldest = fs.get_date(string);
1008                                 oldest_item = i;
1009                         }
1010                 }
1011
1012                 if(oldest_item >= 0)
1013                 {
1014 // Remove index file
1015                         fs.join_names(string,
1016                                 preferences->index_directory,
1017                                 fs.dir_list[oldest_item]->name);
1018 //printf("MWindow::clean_indexes 1 %s\n", string);
1019                         if(remove(string))
1020                                 perror("delete_indexes");
1021                         delete fs.dir_list[oldest_item];
1022                         fs.dir_list.remove_number(oldest_item);
1023
1024 // Remove table of contents if it exists
1025                         strcpy(string2, string);
1026                         char *ptr = strrchr(string2, '.');
1027                         if(ptr)
1028                         {
1029 //printf("MWindow::clean_indexes 2 %s\n", string2);
1030                                 sprintf(ptr, ".toc");
1031                                 remove(string2);
1032                                 sprintf(ptr, ".mkr");
1033                                 remove(string2);
1034                         }
1035                 }
1036
1037                 total_excess--;
1038         }
1039 }
1040
1041 void MWindow::init_awindow()
1042 {
1043         awindow = new AWindow(this);
1044         awindow->create_objects();
1045 }
1046
1047 void MWindow::init_gwindow()
1048 {
1049         gwindow = new GWindow(this);
1050         gwindow->create_objects();
1051 }
1052
1053 void MWindow::init_tipwindow()
1054 {
1055         TipWindow::load_tips(cin_lang);
1056         if( !twindow )
1057                 twindow = new TipWindow(this);
1058         twindow->start();
1059 }
1060
1061 void MWindow::show_warning(int *do_warning, const char *text)
1062 {
1063         if( do_warning && !*do_warning ) return;
1064         if( !wwindow )
1065                 wwindow = new WWindow(this);
1066         wwindow->show_warning(do_warning, text);
1067 }
1068
1069 int MWindow::wait_warning()
1070 {
1071         return wwindow->wait_result();
1072 }
1073
1074 void MWindow::init_theme()
1075 {
1076         Timer timer;
1077         theme = 0;
1078
1079         PluginServer *theme_plugin = 0;
1080         for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1081                 if( plugindb->get(i)->theme &&
1082                     !strcasecmp(preferences->theme, plugindb->get(i)->title) )
1083                         theme_plugin = plugindb->get(i);
1084         }
1085
1086         if( !theme_plugin )
1087                 fprintf(stderr, _("MWindow::init_theme: prefered theme %s not found.\n"),
1088                          preferences->theme);
1089
1090         const char *default_theme = DEFAULT_THEME;
1091         if( !theme_plugin && strcasecmp(preferences->theme, default_theme) ) {
1092                 fprintf(stderr, _("MWindow::init_theme: trying default theme %s\n"),
1093                         default_theme);
1094                 for(int i = 0; i < plugindb->total && !theme_plugin; i++) {
1095                         if( plugindb->get(i)->theme &&
1096                             !strcasecmp(default_theme, plugindb->get(i)->title) )
1097                                 theme_plugin = plugindb->get(i);
1098                 }
1099         }
1100
1101         if(!theme_plugin) {
1102                 fprintf(stderr, _("MWindow::init_theme: theme_plugin not found.\n"));
1103                 exit(1);
1104         }
1105
1106         PluginServer *plugin = new PluginServer(*theme_plugin);
1107         if( plugin->open_plugin(0, preferences, 0, 0) ) {
1108                 fprintf(stderr, _("MWindow::init_theme: unable to load theme %s\n"),
1109                         theme_plugin->title);
1110                 exit(1);
1111         }
1112
1113         theme = plugin->new_theme();
1114         theme->mwindow = this;
1115         strcpy(theme->path, plugin->path);
1116         delete plugin;
1117
1118 // Load default images & settings
1119         theme->Theme::initialize();
1120 // Load user images & settings
1121         theme->initialize();
1122 // Create menus with user colors
1123         theme->build_menus();
1124         init_menus();
1125
1126         theme->sort_image_sets();
1127         theme->check_used();
1128 //printf("MWindow::init_theme %d total_time=%d\n", __LINE__, (int)timer.get_difference());
1129 }
1130
1131 void MWindow::init_3d()
1132 {
1133         playback_3d = new Playback3D(this);
1134         playback_3d->create_objects();
1135 }
1136
1137 void MWindow::init_edl()
1138 {
1139         edl = new EDL;
1140         edl->create_objects();
1141         fill_preset_defaults(default_standard, edl->session);
1142         edl->load_defaults(defaults);
1143         edl->session->brender_start = edl->session->brender_end = 0;
1144         edl->create_default_tracks();
1145         edl->tracks->update_y_pixels(theme);
1146 }
1147
1148 void MWindow::init_compositor()
1149 {
1150         cwindow = new CWindow(this);
1151         cwindow->create_objects();
1152 }
1153
1154 void MWindow::init_levelwindow()
1155 {
1156         lwindow = new LevelWindow(this);
1157         lwindow->create_objects();
1158 }
1159
1160 VWindow *MWindow::get_viewer(int start_it, int idx)
1161 {
1162         vwindows_lock->lock("MWindow::get_viewer");
1163         VWindow *vwindow = idx >= 0 && idx < vwindows.size() ? vwindows[idx] : 0;
1164         if( !vwindow ) idx = vwindows.size();
1165         while( !vwindow && --idx >= 0 ) {
1166                 VWindow *vwin = vwindows[idx];
1167                 if( !vwin->is_running() || !vwin->get_edl() )
1168                         vwindow = vwin;
1169         }
1170         if( !vwindow ) {
1171                 vwindow = new VWindow(this);
1172                 vwindow->load_defaults();
1173                 vwindow->create_objects();
1174                 vwindows.append(vwindow);
1175         }
1176         vwindows_lock->unlock();
1177         if( start_it ) vwindow->start();
1178         return vwindow;
1179 }
1180
1181 ZWindow *MWindow::get_mixer(Mixer *&mixer)
1182 {
1183         zwindows_lock->lock("MWindow::get_mixer");
1184         if( !mixer ) mixer = edl->mixers.new_mixer();
1185         ZWindow *zwindow = 0;
1186         for( int i=0; !zwindow && i<zwindows.size(); ++i )
1187                 if( zwindows[i]->idx < 0 ) zwindow = zwindows[i];
1188         if( !zwindow )
1189                 zwindows.append(zwindow = new ZWindow(this));
1190         zwindow->idx = mixer->idx;
1191         zwindows_lock->unlock();
1192         return zwindow;
1193 }
1194
1195 void MWindow::del_mixer(ZWindow *zwindow)
1196 {
1197         zwindows_lock->lock("MWindow::del_mixer 0");
1198         edl->mixers.del_mixer(zwindow->idx);
1199         if( session->selected_zwindow >= 0 ) {
1200                 int i = zwindows.number_of(zwindow);
1201                 if( i >= 0 && i < session->selected_zwindow )
1202                         --session->selected_zwindow;
1203                 else if( i == session->selected_zwindow )
1204                         session->selected_zwindow = -1;
1205         }
1206         zwindows_lock->unlock();
1207         gui->lock_window("MWindow::del_mixer 1");
1208         gui->update_mixers(0, -1);
1209         gui->unlock_window();
1210 }
1211
1212 void MWindow::start_mixer()
1213 {
1214         Mixer *mixer = 0;
1215         ZWindow *zwindow = get_mixer(mixer);
1216         const char *title = 0;
1217
1218         for( Track *track=edl->tracks->first; track!=0; track=track->next ) {
1219                 PatchGUI *patchgui = get_patchgui(track);
1220                 if( !patchgui || !patchgui->mixer ) continue;
1221                 mixer->mixer_ids.append(track->get_mixer_id());
1222                 if( !title ) title = track->title;
1223         }
1224
1225         session->selected_zwindow = -1;
1226         gui->lock_window("MWindow::start_mixer");
1227         gui->update_mixers(0, 0);
1228         gui->unlock_window();
1229
1230         zwindow->set_title(title);
1231         zwindow->start();
1232         refresh_mixers();
1233 }
1234
1235 int MWindow::mixer_track_active(Track *track)
1236 {
1237         int i = session->selected_zwindow;
1238         if( i < 0 || i >= zwindows.size() ) return 0;
1239         ZWindow *zwindow = zwindows[i];
1240         Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1241         if( !mixer ) return 0;
1242         int n = mixer->mixer_ids.number_of(track->get_mixer_id());
1243         return n >= 0 ? 1 : 0;
1244 }
1245
1246 void MWindow::update_mixer_tracks()
1247 {
1248         zwindows_lock->lock("MixPatch::handle_event");
1249         int i = session->selected_zwindow;
1250         if( i >= 0 && i < zwindows.size() ) {
1251                 ZWindow *zwindow = zwindows[i];
1252                 zwindow->update_mixer_ids();
1253         }
1254         zwindows_lock->unlock();
1255 }
1256
1257 void MWindow::queue_mixers(EDL *edl, int command, int wait_tracking,
1258                 int use_inout, int update_refresh, int toggle_audio, int loop_play)
1259 {
1260         zwindows_lock->lock("MWindow::queue_mixers");
1261         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1262                 ZWindow *zwindow = zwindows[vidx];
1263                 if( zwindow->idx < 0 ) continue;
1264                 Mixer *mixer = edl->mixers.get_mixer(zwindow->idx);
1265                 if( !mixer || !mixer->mixer_ids.size() ) continue;
1266                 int k = -1;
1267                 for( Track *track = edl->tracks->first; k<0 && track!=0; track=track->next ) {
1268                         if( track->data_type != TRACK_VIDEO ) continue;
1269                         int mixer_id = track->get_mixer_id();
1270                         k = mixer->mixer_ids.size();
1271                         while( --k >= 0 && mixer_id != mixer->mixer_ids[k] );
1272                 }
1273                 if( k < 0 ) continue;
1274                 EDL *mixer_edl = new EDL(this->edl);
1275                 mixer_edl->create_objects();
1276                 mixer_edl->copy_all(edl);
1277                 mixer_edl->remove_vwindow_edls();
1278                 for( Track *track = mixer_edl->tracks->first; track!=0; track=track->next ) {
1279                         k = mixer->mixer_ids.size();
1280                         while( --k >= 0 && track->get_mixer_id() != mixer->mixer_ids[k] );
1281                         if( k >= 0 ) {
1282                                 track->record = 1;
1283                                 track->play = track->data_type == TRACK_VIDEO ? 1 : 0;
1284                         }
1285                         else
1286                                 track->record = track->play = 0;
1287                 }
1288                 zwindow->change_source(mixer_edl);
1289                 zwindow->issue_command(command,
1290                         wait_tracking, use_inout, update_refresh, toggle_audio, loop_play);
1291         }
1292         zwindows_lock->unlock();
1293 }
1294
1295 void MWindow::refresh_mixers(int dir)
1296 {
1297         int command = dir >= 0 ? CURRENT_FRAME : LAST_FRAME;
1298         queue_mixers(edl,command,0,0,1,0,0);
1299 }
1300
1301 void MWindow::stop_mixers()
1302 {
1303         for( int vidx=0; vidx<zwindows.size(); ++vidx ) {
1304                 ZWindow *zwindow = zwindows[vidx];
1305                 if( zwindow->idx < 0 ) continue;
1306                 zwindow->issue_command(STOP, 0, 0, 0, 0, 0);
1307         }
1308 }
1309
1310 void MWindow::close_mixers(int destroy)
1311 {
1312         ArrayList<ZWindow*> closed;
1313         zwindows_lock->lock("MWindow::close_mixers");
1314         for( int i=zwindows.size(); --i>=0; ) {
1315                 ZWindow *zwindow = zwindows[i];
1316                 if( zwindow->idx < 0 ) continue;
1317                 zwindow->destroy = destroy;
1318                 ZWindowGUI *zgui = zwindow->zgui;
1319                 zgui->lock_window("MWindow::select_zwindow 0");
1320                 zgui->set_done(0);
1321                 zgui->unlock_window();
1322                 closed.append(zwindow);
1323         }
1324         zwindows_lock->unlock();
1325         for( int i=0; i<closed.size(); ++i ) {
1326                 ZWindow *zwindow = closed[i];
1327                 zwindow->join();
1328         }
1329 }
1330
1331 ZWindow *MWindow::create_mixer(Indexable *indexable)
1332 {
1333         ArrayList<Indexable*> new_assets;
1334         new_assets.append(indexable);
1335         Track *track = edl->tracks->last;
1336         load_assets(&new_assets, 0, LOADMODE_NEW_TRACKS, 0, 0, 0, 0, 0, 0);
1337         track = !track ? edl->tracks->first : track->next;
1338         Mixer *mixer = 0;
1339         ZWindow *zwindow = get_mixer(mixer);
1340         while( track ) {
1341                 track->play = track->record = 0;
1342                 if( track->data_type == TRACK_VIDEO ) {
1343                         sprintf(track->title, _("Mixer %d"), zwindow->idx);
1344                 }
1345                 mixer->mixer_ids.append(track->get_mixer_id());
1346                 track = track->next;
1347         }
1348         if(  indexable->is_asset ) {
1349                 char *path = indexable->path;
1350                 char *tp = strrchr(path, '/');
1351                 if( !tp ) tp = path; else ++tp;
1352                 zwindow->set_title(tp);
1353         }
1354         else {
1355                 char *title = ((EDL*)indexable)->local_session->clip_title;
1356                 zwindow->set_title(title);
1357         }
1358         return zwindow;
1359 }
1360
1361 void MWindow::create_mixers()
1362 {
1363         if( !session->drag_assets->size() &&
1364             !session->drag_clips->size() ) return;
1365         undo->update_undo_before();
1366
1367         select_zwindow(0);
1368         ArrayList<ZWindow *>new_mixers;
1369
1370         for( int i=0; i<session->drag_assets->size(); ++i ) {
1371                 Indexable *indexable = session->drag_assets->get(i);
1372                 if( !indexable->have_video() ) continue;
1373                 ZWindow *zwindow = create_mixer(indexable);
1374                 new_mixers.append(zwindow);
1375         }
1376         for( int i=0; i<session->drag_clips->size(); ++i ) {
1377                 Indexable *indexable = (Indexable*)session->drag_clips->get(i);
1378                 if( !indexable->have_video() ) continue;
1379                 ZWindow *zwindow = create_mixer(indexable);
1380                 new_mixers.append(zwindow);
1381         }
1382
1383         tile_mixers();
1384         for( int i=0; i<new_mixers.size(); ++i )
1385                 new_mixers[i]->start();
1386
1387         refresh_mixers();
1388         save_backup();
1389         undo->update_undo_after(_("create mixers"), LOAD_ALL);
1390         restart_brender();
1391         gui->update(1, 2, 1, 1, 1, 1, 0);
1392         sync_parameters(CHANGE_ALL);
1393 }
1394
1395 void MWindow::open_mixers()
1396 {
1397         for( int i=0; i<edl->mixers.size(); ++i ) {
1398                 Mixer *mixer = edl->mixers[i];
1399                 ZWindow *zwindow = get_mixer(mixer);
1400                 zwindow->set_title(mixer->title);
1401                 zwindow->start();
1402         }
1403         refresh_mixers();
1404 }
1405
1406 int MWindow::select_zwindow(ZWindow *zwindow)
1407 {
1408         int ret = 0, n = zwindows.number_of(zwindow);
1409         if( session->selected_zwindow != n ) {
1410                 session->selected_zwindow = n;
1411                 for( int i=0; i<zwindows.size(); ++i ) {
1412                         ZWindow *zwindow = zwindows[i];
1413                         if( zwindow->idx < 0 ) continue;
1414                         ZWindowGUI *zgui = zwindow->zgui;
1415                         zgui->lock_window("MWindow::select_zwindow 0");
1416                         zwindow->highlighted = i == n ? 1 : 0;
1417                         if( zgui->draw_overlays() )
1418                                 zgui->canvas->get_canvas()->flash(1);
1419                         zgui->unlock_window();
1420                 }
1421                 ret = 1;
1422                 gui->lock_window("MWindow::select_window 1");
1423                 gui->update_mixers(0, -1);
1424                 gui->unlock_window();
1425         }
1426         return ret;
1427 }
1428
1429 void MWindow::tile_mixers()
1430 {
1431         int nz = 0;
1432         for( int i=0; i<zwindows.size(); ++i ) {
1433                 ZWindow *zwindow = zwindows[i];
1434                 if( zwindow->idx < 0 ) continue;
1435                 ++nz;
1436         }
1437         if( !nz ) return;
1438         int zn = ceil(sqrt(nz));
1439         int x1 = 1 + gui->get_x(), x2 = cwindow->gui->get_x();
1440         int y1 = 1, y2 = gui->get_y();
1441         int rw = gui->get_root_w(0), rh = gui->get_root_h(0);
1442         if( x1 < 0 ) x1 = 0;
1443         if( y1 < 0 ) y1 = 0;
1444         if( x2 > rw ) x2 = rw;
1445         if( y2 > rh ) y2 = rh;
1446         int dx = x2 - x1, dy = y2 - y1;
1447         int zw = dx / zn;
1448         int lt = BC_DisplayInfo::get_left_border();
1449         int top = BC_DisplayInfo::get_top_border();
1450         int bw = lt + BC_DisplayInfo::get_right_border();  // borders
1451         int bh = top + BC_DisplayInfo::get_bottom_border();
1452         int zx = 0, zy = 0;  // window origins
1453         int mw = 10+10, mh = 10+10; // canvas margins
1454         int rsz = 0, n = 0, dz = 0;
1455         int ow = edl->session->output_w, oh = edl->session->output_h;
1456         for( int i=0; i<zwindows.size(); ++i ) {
1457                 ZWindow *zwindow = zwindows[i];
1458                 if( zwindow->idx < 0 ) continue;
1459                 int ww = zw - bw, hh = (ww - mw) * oh / ow + mh, zh = hh + bh;
1460                 if( rsz < hh ) rsz = hh;
1461                 int xx = zx + x1, yy = zy + y1;
1462                 int mx = x2 - zw, my = y2 - zh;
1463                 if( xx > mx ) xx = mx;
1464                 if( yy > my ) yy = my;
1465                 xx += lt + dz;  yy += top + dz;
1466                 zwindow->reposition(xx,yy, ww,hh);
1467                 if( zwindow->running() ) {
1468                         ZWindowGUI *gui = (ZWindowGUI *)zwindow->get_gui();
1469                         gui->lock_window("MWindow::tile_mixers");
1470                         gui->BC_WindowBase::reposition_window(xx,yy, ww,hh);
1471                         gui->unlock_window();
1472                 }
1473                 if( ++n >= zn ) {
1474                         n = 0;  rsz += bh;
1475                         if( (zy += rsz) > (dy - rsz) ) dz += 10;
1476                         rsz = 0;
1477                         zx = 0;
1478                 }
1479                 else
1480                         zx += zw;
1481         }
1482 }
1483
1484 void MWindow::init_cache()
1485 {
1486         audio_cache = new CICache(preferences);
1487         video_cache = new CICache(preferences);
1488         frame_cache = new FrameCache;
1489         wave_cache = new WaveCache;
1490 }
1491
1492 void MWindow::init_channeldb()
1493 {
1494         channeldb_buz->load("channeldb_buz");
1495         channeldb_v4l2jpeg->load("channeldb_v4l2jpeg");
1496 }
1497
1498 void MWindow::init_menus()
1499 {
1500         char string[BCTEXTLEN];
1501
1502         // Color Models
1503         BC_CModels::to_text(string, BC_RGB888);
1504         colormodels.append(new ColormodelItem(string, BC_RGB888));
1505         BC_CModels::to_text(string, BC_RGBA8888);
1506         colormodels.append(new ColormodelItem(string, BC_RGBA8888));
1507 //      BC_CModels::to_text(string, BC_RGB161616);
1508 //      colormodels.append(new ColormodelItem(string, BC_RGB161616));
1509 //      BC_CModels::to_text(string, BC_RGBA16161616);
1510 //      colormodels.append(new ColormodelItem(string, BC_RGBA16161616));
1511         BC_CModels::to_text(string, BC_RGB_FLOAT);
1512         colormodels.append(new ColormodelItem(string, BC_RGB_FLOAT));
1513         BC_CModels::to_text(string, BC_RGBA_FLOAT);
1514         colormodels.append(new ColormodelItem(string, BC_RGBA_FLOAT));
1515         BC_CModels::to_text(string, BC_YUV888);
1516         colormodels.append(new ColormodelItem(string, BC_YUV888));
1517         BC_CModels::to_text(string, BC_YUVA8888);
1518         colormodels.append(new ColormodelItem(string, BC_YUVA8888));
1519 //      BC_CModels::to_text(string, BC_YUV161616);
1520 //      colormodels.append(new ColormodelItem(string, BC_YUV161616));
1521 //      BC_CModels::to_text(string, BC_YUVA16161616);
1522 //      colormodels.append(new ColormodelItem(string, BC_YUVA16161616));
1523
1524 #define ILACEPROJECTMODELISTADD(x) ilacemode_to_text(string, x); \
1525                            interlace_project_modes.append(new InterlacemodeItem(string, x));
1526
1527 #define ILACEASSETMODELISTADD(x) ilacemode_to_text(string, x); \
1528                            interlace_asset_modes.append(new InterlacemodeItem(string, x));
1529
1530 #define ILACEFIXMETHODLISTADD(x) ilacefixmethod_to_text(string, x); \
1531                            interlace_asset_fixmethods.append(new InterlacefixmethodItem(string, x));
1532
1533         // Interlacing Modes
1534         ILACEASSETMODELISTADD(ILACE_MODE_UNDETECTED); // Not included in the list for the project options.
1535
1536         ILACEASSETMODELISTADD(ILACE_MODE_TOP_FIRST);
1537         ILACEPROJECTMODELISTADD(ILACE_MODE_TOP_FIRST);
1538
1539         ILACEASSETMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1540         ILACEPROJECTMODELISTADD(ILACE_MODE_BOTTOM_FIRST);
1541
1542         ILACEASSETMODELISTADD(ILACE_MODE_NOTINTERLACED);
1543         ILACEPROJECTMODELISTADD(ILACE_MODE_NOTINTERLACED);
1544
1545         // Interlacing Fixing Methods
1546         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_NONE);
1547         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_UPONE);
1548         ILACEFIXMETHODLISTADD(ILACE_FIXMETHOD_DOWNONE);
1549 }
1550
1551 void MWindow::init_indexes()
1552 {
1553         mainindexes = new MainIndexes(this);
1554         mainindexes->start_loop();
1555 }
1556
1557 void MWindow::init_gui()
1558 {
1559         gui = new MWindowGUI(this);
1560         gui->create_objects();
1561         gui->load_defaults(defaults);
1562 }
1563
1564 void MWindow::init_signals()
1565 {
1566         sighandler = new SigHandler;
1567         sighandler->initialize("/tmp/cinelerra_%d.dmp");
1568 ENABLE_BUFFER
1569 }
1570
1571 void MWindow::init_render()
1572 {
1573         render = new Render(this);
1574         create_bd = new CreateBD_Thread(this);
1575         create_dvd = new CreateDVD_Thread(this);
1576         batch_render = new BatchRenderThread(this);
1577 }
1578
1579 void MWindow::init_exportedl()
1580 {
1581         exportedl = new ExportEDL(this);
1582 }
1583
1584 void MWindow::init_brender()
1585 {
1586         if(preferences->use_brender && !brender)
1587         {
1588                 brender_lock->lock("MWindow::init_brender 1");
1589                 brender = new BRender(this);
1590                 brender->initialize();
1591                 session->brender_end = 0;
1592                 brender_lock->unlock();
1593         }
1594         else
1595         if(!preferences->use_brender && brender)
1596         {
1597                 brender_lock->lock("MWindow::init_brender 2");
1598                 delete brender;
1599                 brender = 0;
1600                 session->brender_end = 0;
1601                 brender_lock->unlock();
1602         }
1603         brender_active = 0;
1604         stop_brender();
1605 }
1606
1607 void MWindow::restart_brender()
1608 {
1609 //printf("MWindow::restart_brender 1\n");
1610         if( !brender_active || !preferences->use_brender ) return;
1611         if( !brender ) return;
1612         brender->restart(edl);
1613 }
1614
1615 void MWindow::stop_brender()
1616 {
1617         if( !brender ) return;
1618 // cannot be holding mwindow->gui display lock
1619         brender->stop();
1620 }
1621
1622 int MWindow::brender_available(int position)
1623 {
1624         int result = 0;
1625         brender_lock->lock("MWindow::brender_available 1");
1626         if(brender && brender_active)
1627         {
1628                 if(brender->map_valid)
1629                 {
1630                         brender->map_lock->lock("MWindow::brender_available 2");
1631                         if(position < brender->map_size &&
1632                                 position >= 0)
1633                         {
1634 //printf("MWindow::brender_available 1 %d %d\n", position, brender->map[position]);
1635                                 if(brender->map[position] == BRender::RENDERED)
1636                                         result = 1;
1637                         }
1638                         brender->map_lock->unlock();
1639                 }
1640         }
1641         brender_lock->unlock();
1642         return result;
1643 }
1644
1645 void MWindow::set_brender_active(int v, int update)
1646 {
1647         if( !preferences->use_brender ) v = 0;
1648         brender_active = v;
1649         gui->mainmenu->brender_active->set_checked(v);
1650         if( v != 0 ) {
1651                 edl->session->brender_start = edl->local_session->get_selectionstart(1);
1652                 edl->session->brender_end = edl->local_session->get_selectionend(1);
1653
1654                 if(EQUIV(edl->session->brender_end, edl->session->brender_start)) {
1655                         edl->session->brender_end = edl->tracks->total_video_length();
1656                 }
1657                 restart_brender();
1658         }
1659         else {
1660                 edl->session->brender_start = edl->session->brender_end = 0;
1661                 gui->unlock_window();
1662                 stop_brender();
1663                 gui->lock_window("MWindow::set_brender_active");
1664         }
1665         if( update ) {
1666                 gui->update_timebar(0);
1667                 gui->draw_overlays(1);
1668         }
1669 }
1670
1671 int MWindow::has_commercials()
1672 {
1673 #ifdef HAVE_COMMERCIAL
1674         return theme->use_commercials;
1675 #else
1676         return 0;
1677 #endif
1678 }
1679
1680 void MWindow::init_commercials()
1681 {
1682 #ifdef HAVE_COMMERCIAL
1683         if( !commercials ) {
1684                 commercials = new Commercials(this);
1685                 commercial_active = 0;
1686         }
1687         else
1688                 commercials->add_user();
1689 #endif
1690 }
1691
1692 void MWindow::commit_commercial()
1693 {
1694 #ifdef HAVE_COMMERCIAL
1695         if( !commercial_active ) return;
1696         commercial_active = 0;
1697         if( !commercials ) return;
1698         commercials->commitDb();
1699 #endif
1700 }
1701
1702 void MWindow::undo_commercial()
1703 {
1704 #ifdef HAVE_COMMERCIAL
1705         if( !commercial_active ) return;
1706         commercial_active = 0;
1707         if( !commercials ) return;
1708         commercials->undoDb();
1709 #endif
1710 }
1711
1712 int MWindow::put_commercial()
1713 {
1714         int result = 0;
1715 #ifdef HAVE_COMMERCIAL
1716         double start = edl->local_session->get_selectionstart();
1717         double end = edl->local_session->get_selectionend();
1718         if( start >= end ) return 0;
1719
1720         const char *errmsg = 0;
1721         int count = 0;
1722         Tracks *tracks = edl->tracks;
1723         //check it
1724         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1725                 if( track->data_type != TRACK_VIDEO ) continue;
1726                 if( !track->record ) continue;
1727                 if( count > 0 ) { errmsg = _("multiple video tracks"); break; }
1728                 ++count;
1729                 int64_t units_start = track->to_units(start,0);
1730                 int64_t units_end = track->to_units(end,0);
1731                 Edits *edits = track->edits;
1732                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1733                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1734                 if(!edit1 && !edit2) continue;  // nothing selected
1735                 if(!edit2) {                    // edit2 beyond end of track
1736                         edit2 = edits->last;
1737                         units_end = edits->length();
1738                 }
1739                 if(edit1 != edit2) { errmsg = _("crosses edits"); break; }
1740                 Indexable *indexable = edit1->get_source();
1741                 if( !indexable->is_asset ) { errmsg = _("not asset"); break; }
1742         }
1743         //run it
1744         for(Track *track=tracks->first; track && !errmsg; track=track->next) {
1745                 if( track->data_type != TRACK_VIDEO ) continue;
1746                 if( !track->record ) continue;
1747                 int64_t units_start = track->to_units(start,0);
1748                 int64_t units_end = track->to_units(end,0);
1749                 Edits *edits = track->edits;
1750                 Edit *edit1 = edits->editof(units_start, PLAY_FORWARD, 0);
1751                 Edit *edit2 = edits->editof(units_end, PLAY_FORWARD, 0);
1752                 if(!edit1 && !edit2) continue;  // nothing selected
1753                 if(!edit2) {                    // edit2 beyond end of track
1754                         edit2 = edits->last;
1755                         units_end = edits->length();
1756                 }
1757                 Indexable *indexable = edit1->get_source();
1758                 Asset *asset = (Asset *)indexable;
1759                 File *file = video_cache->check_out(asset, edl);
1760                 if( !file ) { errmsg = _("no file"); break; }
1761                 int64_t edit_length = units_end - units_start;
1762                 int64_t edit_start = units_start - edit1->startproject + edit1->startsource;
1763                 result = commercials->put_clip(file, edit1->channel,
1764                         track->from_units(edit_start), track->from_units(edit_length));
1765                 video_cache->check_in(asset);
1766                 if( result ) { errmsg = _("db failed"); break; }
1767         }
1768         if( errmsg ) {
1769                 char string[BCTEXTLEN];
1770                 sprintf(string, _("put_commercial: %s"), errmsg);
1771                 MainError::show_error(string);
1772                 undo_commercial();
1773                 result = 1;
1774         }
1775 #endif
1776         return result;
1777 }
1778
1779 void MWindow::stop_playback(int wait)
1780 {
1781         gui->stop_drawing();
1782
1783         cwindow->stop_playback(wait);
1784
1785         for(int i = 0; i < vwindows.size(); i++) {
1786                 VWindow *vwindow = vwindows[i];
1787                 if( !vwindow->is_running() ) continue;
1788                 vwindow->stop_playback(wait);
1789         }
1790         for(int i = 0; i < zwindows.size(); i++) {
1791                 ZWindow *zwindow = zwindows[i];
1792                 if( zwindow->idx < 0 ) continue;
1793                 zwindow->stop_playback(wait);
1794         }
1795 }
1796
1797 void MWindow::stop_transport()
1798 {
1799         gui->stop_transport(gui->get_window_lock() ? "MWindow::stop_transport" : 0);
1800 }
1801
1802 void MWindow::beep(double freq, double secs, double gain)
1803 {
1804         if( !proxy_beep ) proxy_beep = new ProxyBeep(this);
1805         proxy_beep->tone(freq, secs, gain);
1806 }
1807
1808 int MWindow::load_filenames(ArrayList<char*> *filenames,
1809         int load_mode,
1810         int update_filename)
1811 {
1812         ArrayList<EDL*> new_edls;
1813         ArrayList<Asset*> new_assets;
1814         ArrayList<File*> new_files;
1815         const int debug = 0;
1816 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1817
1818 //      save_defaults();
1819         gui->start_hourglass();
1820
1821 // Need to stop playback since tracking depends on the EDL not getting
1822 // deleted.
1823         gui->unlock_window();
1824         stop_playback(1);
1825         gui->lock_window("MWindow::load_filenames 0");
1826
1827 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1828         undo->update_undo_before();
1829
1830
1831 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1832
1833 // Define new_edls and new_assets to load
1834         int result = 0, ftype = -1;
1835
1836         for( int i=0; i<filenames->size(); ++i ) {
1837 // Get type of file
1838                 File *new_file = new File;
1839                 Asset *new_asset = new Asset(filenames->get(i));
1840                 EDL *new_edl = new EDL;
1841                 char string[BCTEXTLEN];
1842
1843                 new_edl->create_objects();
1844                 new_edl->copy_session(edl, -1);
1845                 new_file->set_program(edl->session->program_no);
1846
1847                 sprintf(string, _("Loading %s"), new_asset->path);
1848                 gui->show_message(string);
1849 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1850
1851                 ftype = new_file->open_file(preferences, new_asset, 1, 0);
1852 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1853
1854                 result = 1;
1855                 switch( ftype ) {
1856 // Convert media file to EDL
1857                 case FILE_OK:
1858 // Warn about odd image dimensions
1859                         if( new_asset->video_data &&
1860                             ((new_asset->width % 2) || (new_asset->height % 2)) ) {
1861                                 char string[BCTEXTLEN];
1862                                 sprintf(string, _("%s's resolution is %dx%d.\nImages with odd dimensions may not decode properly."),
1863                                         new_asset->path, new_asset->width, new_asset->height);
1864                                 MainError::show_error(string);
1865                         }
1866
1867                         if( new_asset->program >= 0 &&
1868                             edl->session->program_no != new_asset->program ) {
1869                                 char string[BCTEXTLEN];
1870                                 sprintf(string, _("%s's index was built for program number %d\n"
1871                                         "Playback preference is %d.\n  Using program %d."),
1872                                         new_asset->path, new_asset->program,
1873                                         edl->session->program_no, new_asset->program);
1874                                 MainError::show_error(string);
1875                         }
1876
1877                         if( load_mode != LOADMODE_RESOURCESONLY ) {
1878                                 RecordLabels *labels = edl->session->label_cells ?
1879                                         new RecordLabels(new_file) : 0;
1880                                 asset_to_edl(new_edl, new_asset, labels);
1881                                 new_edls.append(new_edl);
1882                                 new_edl->add_user();
1883                                 delete labels;
1884                         }
1885                         else {
1886                                 new_assets.append(new_asset);
1887                                 new_asset->add_user();
1888                         }
1889
1890 // Set filename to nothing for assets since save EDL would overwrite them.
1891                         if( load_mode == LOADMODE_REPLACE ||
1892                             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
1893                                 set_filename("");
1894 // Reset timeline position
1895                                 for( int i=0; i<TOTAL_PANES; ++i ) {
1896                                         new_edl->local_session->view_start[i] = 0;
1897                                         new_edl->local_session->track_start[i] = 0;
1898                                 }
1899                         }
1900
1901                         result = 0;
1902                         break;
1903
1904 // File not found
1905                 case FILE_NOT_FOUND:
1906                         sprintf(string, _("Failed to open %s"), new_asset->path);
1907                         gui->show_message(string, theme->message_error);
1908                         gui->update_default_message();
1909                         break;
1910
1911 // Unknown format
1912                 case FILE_UNRECOGNIZED_CODEC: {
1913 // Test index file
1914                         { IndexFile indexfile(this, new_asset);
1915                         if( !(result = indexfile.open_index()) )
1916                                 indexfile.close_index(); }
1917
1918 // Test existing EDLs
1919                         for( int j=0; result && j<new_edls.total; ++j ) {
1920                                 Asset *old_asset = new_edls[j]->assets->get_asset(new_asset->path);
1921                                 if( old_asset ) {
1922                                         new_asset->copy_from(old_asset,1);
1923                                         result = 0;
1924                                 }
1925                         }
1926                         if( result ) {
1927                                 Asset *old_asset = edl->assets->get_asset(new_asset->path);
1928                                 if( old_asset ) {
1929                                         new_asset->copy_from(old_asset,1);
1930                                         result = 0;
1931                                 }
1932                         }
1933
1934 // Prompt user
1935                         if( result ) {
1936                                 char string[BCTEXTLEN];
1937                                 FileSystem fs;
1938                                 fs.extract_name(string, new_asset->path);
1939
1940                                 strcat(string, _("'s format couldn't be determined."));
1941                                 new_asset->audio_data = 1;
1942                                 new_asset->format = FILE_PCM;
1943                                 new_asset->channels = defaults->get("AUDIO_CHANNELS", 2);
1944                                 new_asset->sample_rate = defaults->get("SAMPLE_RATE", 44100);
1945                                 new_asset->bits = defaults->get("AUDIO_BITS", 16);
1946                                 new_asset->byte_order = defaults->get("BYTE_ORDER", 1);
1947                                 new_asset->signed_ = defaults->get("SIGNED_", 1);
1948                                 new_asset->header = defaults->get("HEADER", 0);
1949
1950                                 FileFormat fwindow(this);
1951                                 fwindow.create_objects(new_asset, string);
1952                                 result = fwindow.run_window();
1953
1954                                 defaults->update("AUDIO_CHANNELS", new_asset->channels);
1955                                 defaults->update("SAMPLE_RATE", new_asset->sample_rate);
1956                                 defaults->update("AUDIO_BITS", new_asset->bits);
1957                                 defaults->update("BYTE_ORDER", new_asset->byte_order);
1958                                 defaults->update("SIGNED_", new_asset->signed_);
1959                                 defaults->update("HEADER", new_asset->header);
1960                                 save_defaults();
1961                         }
1962
1963 // Append to list
1964                         if( !result ) {
1965 // Recalculate length
1966                                 delete new_file;
1967                                 new_file = new File;
1968                                 result = new_file->open_file(preferences, new_asset, 1, 0);
1969
1970                                 if( load_mode != LOADMODE_RESOURCESONLY ) {
1971                                         RecordLabels *labels = edl->session->label_cells ?
1972                                                 new RecordLabels(new_file) : 0;
1973                                         asset_to_edl(new_edl, new_asset, labels);
1974                                         new_edls.append(new_edl);
1975                                         new_edl->add_user();
1976                                         delete labels;
1977                                 }
1978                                 else {
1979                                         new_assets.append(new_asset);
1980                                         new_asset->add_user();
1981                                 }
1982                         }
1983                         else {
1984                                 result = 1;
1985                         }
1986                         break; }
1987
1988                 case FILE_IS_XML: {
1989                         FileXML xml_file;
1990 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1991                         xml_file.read_from_file(filenames->get(i));
1992 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
1993                         const char *cin_version = 0;
1994                         while( !xml_file.read_tag() ) {
1995                                 if( xml_file.tag.title_is("EDL") ) {
1996                                         cin_version = xml_file.tag.get_property("VERSION");
1997                                         break;
1998                                 }
1999                         }
2000                         xml_file.rewind();
2001                         if( !cin_version ) {
2002                                 eprintf(_("XML file %s\n not from cinelerra."),filenames->get(i));
2003                                 char string[BCTEXTLEN];
2004                                 sprintf(string,_("Unknown %s"), filenames->get(i));
2005                                 gui->show_message(string);
2006                                 result = 1;
2007                                 break;
2008                         }
2009                         if( strcmp(cin_version, CINELERRA_VERSION) &&
2010                             strcmp(cin_version, "5.1") ) {
2011                                 char string[BCTEXTLEN];
2012                                 snprintf(string, sizeof(string),
2013                                          _("Warning: XML from cinelerra version %s\n"
2014                                         "Session data may be incompatible."), cin_version);
2015                                 show_warning(&preferences->warn_version, string);
2016                         }
2017                         if( load_mode == LOADMODE_NESTED ) {
2018 // Load temporary EDL for nesting.
2019                                 EDL *nested_edl = new EDL;
2020                                 nested_edl->create_objects();
2021                                 nested_edl->load_xml(&xml_file, LOAD_ALL);
2022 //printf("MWindow::load_filenames %p %s\n", nested_edl, nested_edl->project_path);
2023                                 new_edl->create_nested(nested_edl);
2024                                 new_edl->set_path(filenames->get(i));
2025                                 nested_edl->Garbage::remove_user();
2026                         }
2027                         else {
2028 // Load EDL for pasting
2029                                 new_edl->load_xml(&xml_file, LOAD_ALL);
2030 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2031                                 test_plugins(new_edl, filenames->get(i));
2032 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2033
2034                                 if( load_mode == LOADMODE_REPLACE ||
2035                                     load_mode == LOADMODE_REPLACE_CONCATENATE ) {
2036                                         strcpy(session->filename, filenames->get(i));
2037                                         strcpy(new_edl->local_session->clip_title,
2038                                                 filenames->get(i));
2039                                         if(update_filename)
2040                                                 set_filename(new_edl->local_session->clip_title);
2041                                 }
2042                                 else if( load_mode == LOADMODE_RESOURCESONLY ) {
2043                                         strcpy(new_edl->local_session->clip_title,
2044                                                 filenames->get(i));
2045                                         struct stat st;
2046                                         time_t t = !stat(filenames->get(i),&st) ?
2047                                                 st.st_mtime : time(&t);
2048                                         ctime_r(&t, new_edl->local_session->clip_notes);
2049                                 }
2050                         }
2051
2052                         new_edls.append(new_edl);
2053                         new_edl->add_user();
2054                         result = 0;
2055                         break; }
2056                 }
2057
2058                 new_edl->Garbage::remove_user();
2059                 new_asset->Garbage::remove_user();
2060
2061 // Store for testing index
2062                 new_files.append(new_file);
2063         }
2064
2065 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2066
2067
2068         if(!result) {
2069                 gui->reset_default_message();
2070                 gui->default_message();
2071         }
2072
2073
2074 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2075
2076 // Paste them.
2077 // Don't back up here.
2078         if(new_edls.size())
2079         {
2080 // For pasting, clear the active region
2081                 if(load_mode == LOADMODE_PASTE ||
2082                         load_mode == LOADMODE_NESTED)
2083                 {
2084                         double start = edl->local_session->get_selectionstart();
2085                         double end = edl->local_session->get_selectionend();
2086                         if(!EQUIV(start, end))
2087                                 edl->clear(start,
2088                                         end,
2089                                         edl->session->labels_follow_edits,
2090                                         edl->session->plugins_follow_edits,
2091                                         edl->session->autos_follow_edits);
2092                 }
2093
2094                 paste_edls(&new_edls, load_mode, 0, -1,
2095                         edl->session->labels_follow_edits,
2096                         edl->session->plugins_follow_edits,
2097                         edl->session->autos_follow_edits,
2098                         0); // overwrite
2099         }
2100
2101
2102
2103
2104 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2105
2106 // Add new assets to EDL and schedule assets for index building.
2107         int got_indexes = 0;
2108         for( int i=0; i<new_edls.size(); ++i ) {
2109                 EDL *new_edl = new_edls[i];
2110                 for( int j=0; j<new_edl->nested_edls.size(); ++j ) {
2111                         mainindexes->add_next_asset(0, new_edl->nested_edls[j]);
2112                         edl->nested_edls.update_index(new_edl->nested_edls[j]);
2113                         got_indexes = 1;
2114                 }
2115
2116         }
2117
2118 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2119         for( int i=0; i<new_assets.size(); ++i ) {
2120                 Asset *new_asset = new_assets[i];
2121
2122                 File *new_file = 0;
2123                 int got_it = 0;
2124                 for( int j=0; j<new_files.size(); ++j ) {
2125                         new_file = new_files[j];
2126                         if( !strcmp(new_file->asset->path, new_asset->path) ) {
2127                                 got_it = 1;
2128                                 break;
2129                         }
2130                 }
2131
2132                 mainindexes->add_next_asset(got_it ? new_file : 0, new_asset);
2133                 edl->assets->update(new_asset);
2134                 got_indexes = 1;
2135         }
2136 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2137
2138 // Start examining next batch of index files
2139         if(got_indexes) mainindexes->start_build();
2140 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2141
2142 // Open plugin GUIs
2143         Track *track = edl->tracks->first;
2144         while(track)
2145         {
2146                 for(int j = 0; j < track->plugin_set.size(); j++)
2147                 {
2148                         PluginSet *plugins = track->plugin_set[j];
2149                         Plugin *plugin = plugins->get_first_plugin();
2150
2151                         while(plugin)
2152                         {
2153                                 if(load_mode == LOADMODE_REPLACE ||
2154                                         load_mode == LOADMODE_REPLACE_CONCATENATE)
2155                                 {
2156                                         if(plugin->plugin_type == PLUGIN_STANDALONE &&
2157                                                 plugin->show)
2158                                         {
2159                                                 show_plugin(plugin);
2160                                         }
2161                                 }
2162
2163                                 plugin = (Plugin*)plugin->next;
2164                         }
2165                 }
2166
2167                 track = track->next;
2168         }
2169
2170         // if just opening one new resource in replace mode
2171         if( ftype != FILE_IS_XML &&
2172             ( load_mode == LOADMODE_REPLACE ||
2173               load_mode == LOADMODE_REPLACE_CONCATENATE ) ) {
2174                 select_asset(0, 0);
2175                 edl->session->proxy_scale = 1;
2176                 edl->session->proxy_disabled_scale = 1;
2177                 edl->session->proxy_use_scaler = 0;
2178                 edl->session->proxy_auto_scale = 0;
2179                 edl->session->proxy_beep = 0;
2180                 edl->local_session->preview_start = 0;
2181                 edl->local_session->preview_end = -1;
2182                 edl->local_session->loop_playback = 0;
2183                 edl->local_session->set_selectionstart(0);
2184                 edl->local_session->set_selectionend(0);
2185                 set_brender_active(0, 0);
2186                 fit_selection();
2187                 goto_start();
2188         }
2189
2190         if( ( edl->session->proxy_auto_scale && edl->session->proxy_scale != 1 ) &&
2191             ( load_mode != LOADMODE_REPLACE && load_mode != LOADMODE_REPLACE_CONCATENATE ) ) {
2192                 ArrayList<Indexable *> orig_idxbls;
2193                 for( int i=0; i<new_assets.size(); ++i )
2194                         orig_idxbls.append(new_assets.get(i));
2195                 for( int i=0; i<new_edls.size(); ++i ) {
2196                         EDL *new_edl = new_edls[i];
2197                         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2198                                 if( track->data_type != TRACK_VIDEO ) continue;
2199                                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2200                                         Indexable *idxbl = (Indexable *)edit->asset;
2201                                         if( !idxbl ) continue;
2202                                         if( !idxbl->have_video() ) continue;
2203                                         if( edit->channel != 0 ) continue; // first layer only
2204                                         orig_idxbls.append(edit->asset);
2205                                 }
2206                         }
2207                 }
2208                 gui->unlock_window(); // to update progress bar
2209                 int ret = render_proxy(orig_idxbls);
2210                 gui->lock_window("MWindow::load_filenames");
2211                 if( ret >= 0 && edl->session->proxy_beep ) {
2212                         if( ret > 0 )
2213                                 beep(2000., 1.5, 0.5);
2214                         else
2215                                 beep(4000., 0.25, 0.5);
2216                 }
2217         }
2218
2219 // need to update undo before project, since mwindow is unlocked & a new load
2220 // can begin here.  Should really prevent loading until we're done.
2221 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2222         undo->update_undo_after(_("load"), LOAD_ALL);
2223
2224         for(int i = 0; i < new_edls.size(); i++)
2225         {
2226                 new_edls[i]->remove_user();
2227         }
2228 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2229
2230         new_edls.remove_all();
2231
2232         for(int i = 0; i < new_assets.size(); i++)
2233         {
2234                 new_assets[i]->Garbage::remove_user();
2235         }
2236
2237         new_assets.remove_all();
2238         new_files.remove_all_objects();
2239
2240
2241 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2242         if(load_mode == LOADMODE_REPLACE ||
2243                 load_mode == LOADMODE_REPLACE_CONCATENATE)
2244         {
2245                 session->changes_made = 0;
2246         }
2247         else
2248         {
2249                 session->changes_made = 1;
2250         }
2251
2252         gui->stop_hourglass();
2253
2254
2255 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2256         update_project(load_mode);
2257
2258 if(debug) printf("MWindow::load_filenames %d\n", __LINE__);
2259
2260         return 0;
2261 }
2262
2263 int MWindow::render_proxy(ArrayList<Indexable *> &new_idxbls)
2264 {
2265         Asset *format_asset = new Asset;
2266         format_asset->format = FILE_FFMPEG;
2267         format_asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2268         ProxyRender proxy_render(this, format_asset);
2269         int new_scale = edl->session->proxy_scale;
2270         int use_scaler = edl->session->proxy_use_scaler;
2271
2272         for( int i=0; i<new_idxbls.size(); ++i ) {
2273                 Indexable *orig = new_idxbls.get(i);
2274                 Asset *proxy = proxy_render.add_original(orig, new_scale);
2275                 if( !proxy ) continue;
2276                 FileSystem fs;
2277                 int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2278                 int got_it = exists && // if proxy exists, and is newer than orig
2279                     fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2280                 if( got_it ) continue;
2281                 proxy_render.add_needed(orig, proxy);
2282         }
2283
2284 // render needed proxies
2285         int result = proxy_render.create_needed_proxies(new_scale);
2286         if( !result ) {
2287                 add_proxy(use_scaler,
2288                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2289         }
2290         format_asset->remove_user();
2291         return !result ? proxy_render.needed_proxies.size() : -1;
2292 }
2293
2294 int MWindow::enable_proxy()
2295 {
2296         int ret = 0;
2297         if( edl->session->proxy_scale == 1 &&
2298             edl->session->proxy_disabled_scale != 1 ) {
2299                 int new_scale = edl->session->proxy_disabled_scale;
2300                 int new_use_scaler = edl->session->proxy_use_scaler;
2301                 edl->session->proxy_disabled_scale = 1;
2302                 Asset *asset = new Asset;
2303                 asset->format = FILE_FFMPEG;
2304                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2305                 ret = to_proxy(asset, new_scale, new_use_scaler);
2306                 asset->remove_user();
2307                 if( ret > 0 )
2308                         beep(2000., 1.5, 0.5);
2309         }
2310         return 1;
2311 }
2312
2313 int MWindow::disable_proxy()
2314 {
2315         if( edl->session->proxy_scale != 1 &&
2316             edl->session->proxy_disabled_scale == 1 ) {
2317                 int new_scale = 1;
2318                 int new_use_scaler = edl->session->proxy_use_scaler;
2319                 edl->session->proxy_disabled_scale = edl->session->proxy_scale;
2320                 Asset *asset = new Asset;
2321                 asset->format = FILE_FFMPEG;
2322                 asset->load_defaults(defaults, "PROXY_", 1, 1, 0, 0, 0);
2323                 to_proxy(asset, new_scale, new_use_scaler);
2324                 asset->remove_user();
2325         }
2326         return 1;
2327 }
2328
2329 int MWindow::to_proxy(Asset *asset, int new_scale, int new_use_scaler)
2330 {
2331         ArrayList<Indexable*> orig_idxbls;
2332         ArrayList<Indexable*> proxy_assets;
2333
2334         edl->Garbage::add_user();
2335         save_backup();
2336         undo->update_undo_before(_("proxy"), this);
2337         ProxyRender proxy_render(this, asset);
2338
2339 // revert project to original size from current size
2340 // remove all session proxy assets at the at the current proxy_scale
2341         int proxy_scale = edl->session->proxy_scale;
2342
2343         if( proxy_scale > 1 ) {
2344                 Asset *orig_asset = edl->assets->first;
2345                 for( ; orig_asset; orig_asset=orig_asset->next ) {
2346                         char new_path[BCTEXTLEN];
2347                         proxy_render.to_proxy_path(new_path, orig_asset, proxy_scale);
2348 // test if proxy asset was already added to proxy_assets
2349                         int got_it = 0;
2350                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2351                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2352                         if( got_it ) continue;
2353                         Asset *proxy_asset = edl->assets->get_asset(new_path);
2354                         if( !proxy_asset ) continue;
2355 // add pointer to existing EDL asset if it exists
2356 // EDL won't delete it unless it's the same pointer.
2357                         proxy_assets.append(proxy_asset);
2358                         proxy_asset->add_user();
2359                         orig_idxbls.append(orig_asset);
2360                         orig_asset->add_user();
2361                 }
2362                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2363                         EDL *orig_nested = edl->nested_edls[i];
2364                         char new_path[BCTEXTLEN];
2365                         if( !ProxyRender::from_proxy_path(new_path, orig_nested, proxy_scale) )
2366                                 continue;
2367                         proxy_render.to_proxy_path(new_path, orig_nested, proxy_scale);
2368 // test if proxy asset was already added to proxy_assets
2369                         int got_it = 0;
2370                         for( int i = 0; !got_it && i<proxy_assets.size(); ++i )
2371                                 got_it = !strcmp(proxy_assets[i]->path, new_path);
2372                         if( got_it ) continue;
2373                         Asset *proxy_nested = edl->assets->get_asset(new_path);
2374                         if( !proxy_nested ) continue;
2375 // add pointer to existing EDL asset if it exists
2376 // EDL won't delete it unless it's the same pointer.
2377                         proxy_assets.append(proxy_nested);
2378                         proxy_nested->add_user();
2379                         orig_idxbls.append(orig_nested);
2380                         orig_nested->add_user();
2381                 }
2382
2383 // convert from the proxy assets to the original assets
2384                 edl->set_proxy(1, 0, &proxy_assets, &orig_idxbls);
2385
2386 // remove the references
2387                 for( int i=0; i<proxy_assets.size(); ++i ) {
2388                         Asset *proxy = (Asset *) proxy_assets[i];
2389                         proxy->width = proxy->actual_width;
2390                         proxy->height = proxy->actual_height;
2391                         proxy->remove_user();
2392                         edl->assets->remove_pointer(proxy);
2393                         proxy->remove_user();
2394                 }
2395                 proxy_assets.remove_all();
2396                 for( int i = 0; i < orig_idxbls.size(); i++ )
2397                         orig_idxbls[i]->remove_user();
2398                 orig_idxbls.remove_all();
2399         }
2400
2401         ArrayList<char *> confirm_paths;    // test for new files
2402         confirm_paths.set_array_delete();
2403
2404 // convert to new size if not original size
2405         if( new_scale != 1 ) {
2406                 FileSystem fs;
2407                 Asset *orig = edl->assets->first;
2408                 for( ; orig; orig=orig->next ) {
2409                         Asset *proxy = proxy_render.add_original(orig, new_scale);
2410                         if( !proxy ) continue;
2411                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2412                         int got_it = exists && // if proxy exists, and is newer than orig
2413                             fs.get_date(proxy->path) > fs.get_date(orig->path) ? 1 : 0;
2414                         if( !got_it ) {
2415                                 if( exists ) // prompt user to overwrite
2416                                         confirm_paths.append(cstrdup(proxy->path));
2417                                 proxy_render.add_needed(orig, proxy);
2418                         }
2419                 }
2420                 for( int i=0,n=edl->nested_edls.size(); i<n; ++i ) {
2421                         EDL *orig_nested = edl->nested_edls[i];
2422                         Asset *proxy = proxy_render.add_original(orig_nested, new_scale);
2423                         if( !proxy ) continue;
2424                         int exists = fs.get_size(proxy->path) > 0 ? 1 : 0;
2425                         int got_it = exists && // if proxy exists, and is newer than orig_nested
2426                             fs.get_date(proxy->path) > fs.get_date(orig_nested->path) ? 1 : 0;
2427                         if( !got_it ) {
2428                                 if( exists ) // prompt user to overwrite
2429                                         confirm_paths.append(cstrdup(proxy->path));
2430                                 proxy_render.add_needed(orig_nested, proxy);
2431                         }
2432                 }
2433         }
2434
2435         int result = 0;
2436 // test for existing files
2437         if( confirm_paths.size() ) {
2438                 result = ConfirmSave::test_files(this, &confirm_paths);
2439                 confirm_paths.remove_all_objects();
2440         }
2441
2442         if( !result )
2443                 result = proxy_render.create_needed_proxies(new_scale);
2444
2445         if( !result ) // resize project
2446                 edl->set_proxy(new_scale, new_use_scaler,
2447                         &proxy_render.orig_idxbls, &proxy_render.orig_proxies);
2448
2449         undo->update_undo_after(_("proxy"), LOAD_ALL);
2450         edl->Garbage::remove_user();
2451         restart_brender();
2452
2453         gui->lock_window("MWindow::to_proxy");
2454         update_project(LOADMODE_REPLACE);
2455         gui->unlock_window();
2456
2457         return !result ? proxy_render.needed_proxies.size() : -1;
2458 }
2459
2460 void MWindow::test_plugins(EDL *new_edl, char *path)
2461 {
2462         char string[BCTEXTLEN];
2463
2464 // Do a check whether plugins exist
2465         for( Track *track=new_edl->tracks->first; track; track=track->next ) {
2466                 for( int k=0; k<track->plugin_set.total; ++k ) {
2467                         PluginSet *plugin_set = track->plugin_set[k];
2468                         for( Plugin *plugin = (Plugin*)plugin_set->first;
2469                                         plugin; plugin = (Plugin*)plugin->next ) {
2470                                 if( plugin->plugin_type != PLUGIN_STANDALONE ) continue;
2471 // ok we need to find it in plugindb
2472                                 PluginServer *server =
2473                                         scan_plugindb(plugin->title, track->data_type);
2474                                 if( !server || server->transition ) {
2475                                         sprintf(string,
2476         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2477           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2478                                                 "effect", _(plugin->title), path);
2479                                         MainError::show_error(string);
2480                                 }
2481                         }
2482                 }
2483
2484                 for( Edit *edit=track->edits->first; edit; edit=edit->next ) {
2485                         if( !edit->transition ) continue;
2486 // ok we need to find transition in plugindb
2487                         PluginServer *server =
2488                                 scan_plugindb(edit->transition->title, track->data_type);
2489                         if( !server || !server->transition ) {
2490                                 sprintf(string,
2491         _("The %s '%s' in file '%s' is not part of your installation of Cinelerra.\n"
2492           "The project won't be rendered as it was meant and Cinelerra might crash.\n"),
2493                                         "transition", _(edit->transition->title), path);
2494                                 MainError::show_error(string);
2495                         }
2496                 }
2497         }
2498 }
2499
2500
2501 void MWindow::init_shm(const char *pfn, int64_t min)
2502 {
2503         int64_t result = 0;
2504 // Fix shared memory
2505         FILE *fd = fopen(pfn, "r");
2506         if( fd ) {
2507                 fscanf(fd, "%jd", &result);
2508                 fclose(fd);
2509                 if( result >= min ) return;
2510         }
2511
2512         fd = fopen(pfn, "w");
2513         if( !fd ) return;
2514         fprintf(fd, "0x%jx", min);
2515         fclose(fd);
2516
2517         fd = fopen(pfn, "r");
2518         if( !fd ) {
2519                 eprintf(_("MWindow::init_shm: couldn't open %s for reading.\n"), pfn);
2520                 return;
2521         }
2522
2523         fscanf(fd, "%jd", &result);
2524         fclose(fd);
2525         if( result < min ) {
2526                 eprintf(_("MWindow::init_shm: %s is %p.\n"
2527                         "you probably need to be root, or:\n"
2528                         "as root, run: echo 0x%jx > %s\n"
2529                         "before trying to start cinelerra.\n"
2530                         "It should be at least 0x%jx for Cinelerra.\n"),
2531                         pfn, (void *)result, min, pfn, min);
2532         }
2533 }
2534
2535 void MWindow::create_objects(int want_gui,
2536         int want_new,
2537         char *config_path)
2538 {
2539         const int debug = 0;
2540         if(debug) PRINT_TRACE
2541
2542 // For some reason, init_signals must come after show_splash or the signals won't
2543 // get trapped.
2544         init_signals();
2545         if(debug) PRINT_TRACE
2546         init_3d();
2547
2548         if(debug) PRINT_TRACE
2549         show_splash();
2550
2551         if(debug) PRINT_TRACE
2552         default_standard = default_std();
2553         init_defaults(defaults, config_path);
2554         check_language();
2555         init_preferences();
2556         if(splash_window)
2557                 splash_window->update_status(_("Initializing Plugins"));
2558         init_plugins(this, preferences);
2559         if(debug) PRINT_TRACE
2560         init_ladspa_plugins(this, preferences);
2561         if(debug) PRINT_TRACE
2562         init_plugin_tips(*plugindb, cin_lang);
2563         if(splash_window)
2564                 splash_window->update_status(_("Initializing GUI"));
2565         if(debug) PRINT_TRACE
2566         init_theme();
2567
2568         if(debug) PRINT_TRACE
2569         init_error();
2570
2571         if(splash_window)
2572                 splash_window->update_status(_("Initializing Fonts"));
2573         char string[BCTEXTLEN];
2574         strcpy(string, preferences->plugin_dir);
2575         strcat(string, "/" FONT_SEARCHPATH);
2576         BC_Resources::init_fontconfig(string);
2577         if(debug) PRINT_TRACE
2578
2579 // Default project created here
2580         init_edl();
2581         if(debug) PRINT_TRACE
2582
2583         init_cache();
2584         if(debug) PRINT_TRACE
2585
2586         Timer timer;
2587
2588         init_awindow();
2589         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2590
2591         init_compositor();
2592         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2593
2594 //printf("MWindow::create_objects %d session->show_vwindow=%d\n", __LINE__, session->show_vwindow);
2595         if(session->show_vwindow)
2596                 get_viewer(1, DEFAULT_VWINDOW);
2597         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2598
2599         init_gui();
2600         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2601
2602         init_levelwindow();
2603         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2604
2605         init_indexes();
2606         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2607
2608         init_channeldb();
2609         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2610
2611         init_gwindow();
2612         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2613
2614         init_render();
2615         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2616
2617         init_brender();
2618         init_exportedl();
2619         init_commercials();
2620         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2621         mainprogress = new MainProgress(this, gui);
2622         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2623         undo = new MainUndo(this);
2624
2625         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2626
2627         plugin_guis = new ArrayList<PluginServer*>;
2628         dead_plugins = new ArrayList<PluginServer*>;
2629         keyframe_threads = new ArrayList<KeyFrameThread*>;
2630
2631         if(debug) printf("MWindow::create_objects %d vwindows=%d show_vwindow=%d\n",
2632                 __LINE__,
2633                 vwindows.size(),
2634                 session->show_vwindow);
2635
2636 // Show all vwindows
2637 //      if(session->show_vwindow) {
2638 //              for(int j = 0; j < vwindows.size(); j++) {
2639 //                      VWindow *vwindow = vwindows[j];
2640 //                      if( !vwindow->is_running() ) continue;
2641 //                      if(debug) printf("MWindow::create_objects %d vwindow=%p\n",
2642 //                              __LINE__,
2643 //                              vwindow);
2644 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2645 //                      vwindow->gui->lock_window("MWindow::create_objects 1");
2646 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2647 //                      vwindow->gui->show_window();
2648 //                      if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2649 //                      vwindow->gui->unlock_window();
2650 //              }
2651 //      }
2652
2653
2654         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2655
2656         if(session->show_cwindow)
2657         {
2658                 cwindow->gui->lock_window("MWindow::create_objects 1");
2659                 cwindow->gui->show_window();
2660                 cwindow->gui->unlock_window();
2661         }
2662
2663         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2664         if(session->show_awindow)
2665         {
2666                 awindow->gui->lock_window("MWindow::create_objects 1");
2667                 awindow->gui->show_window();
2668                 awindow->gui->unlock_window();
2669         }
2670
2671         if(debug) printf("MWindow::create_objects %d total_time=%d\n", __LINE__, (int)timer.get_difference());
2672         if(session->show_lwindow)
2673         {
2674                 lwindow->gui->lock_window("MWindow::create_objects 1");
2675                 lwindow->gui->show_window();
2676                 lwindow->gui->unlock_window();
2677         }
2678
2679         if(debug) printf("MWindow::create_objects %d total_time=%d gwindow=%p\n",
2680                 __LINE__,
2681                 (int)timer.get_difference(),
2682                 gwindow->gui);
2683         if(session->show_gwindow)
2684         {
2685                 gwindow->gui->lock_window("MWindow::create_objects 1");
2686                 gwindow->gui->show_window();
2687                 gwindow->gui->unlock_window();
2688         }
2689
2690         if(debug) PRINT_TRACE
2691
2692         gui->lock_window("MWindow::create_objects 1");
2693         gui->mainmenu->load_defaults(defaults);
2694         gui->mainmenu->update_toggles(0);
2695         gui->update_patchbay();
2696         gui->draw_canvas(0, 0);
2697         gui->draw_cursor(1);
2698         gui->show_window();
2699         gui->raise_window();
2700         gui->unlock_window();
2701
2702         if(debug) PRINT_TRACE
2703
2704         if(preferences->use_tipwindow)
2705                 init_tipwindow();
2706         if(debug) PRINT_TRACE
2707
2708         gui->add_keyboard_listener(
2709                 (int (BC_WindowBase::*)(BC_WindowBase *))
2710                 &MWindowGUI::keyboard_listener);
2711
2712         hide_splash();
2713         init_shm("/proc/sys/kernel/shmmax", 0x7fffffff);
2714         init_shm("/proc/sys/kernel/shmmni", 0x4000);
2715         if(debug) PRINT_TRACE
2716
2717         BC_WindowBase::get_resources()->vframe_shm = 1;
2718 }
2719
2720
2721 void MWindow::show_splash()
2722 {
2723 #include "data/heroine_logo9_png.h"
2724         VFrame *frame = new VFramePng(heroine_logo9_png);
2725         BC_DisplayInfo dpyi;
2726         int rw = dpyi.get_root_w(), rh = dpyi.get_root_h();
2727         int rr = (rw < rh ? rw : rh) / 4;
2728         splash_window = new SplashGUI(frame, rr, rr);
2729         splash_window->create_objects();
2730 }
2731
2732 void MWindow::hide_splash()
2733 {
2734         if(splash_window)
2735                 delete splash_window;
2736         splash_window = 0;
2737 }
2738
2739
2740 void MWindow::start()
2741 {
2742 ENABLE_BUFFER
2743 //PRINT_TRACE
2744 //      vwindows[DEFAULT_VWINDOW]->start();
2745         awindow->start();
2746 //PRINT_TRACE
2747         cwindow->start();
2748 //PRINT_TRACE
2749         lwindow->start();
2750 //PRINT_TRACE
2751         gwindow->start();
2752 //PRINT_TRACE
2753 //      Thread::start();
2754 //PRINT_TRACE
2755         playback_3d->start();
2756 //PRINT_TRACE
2757 }
2758
2759 void MWindow::run()
2760 {
2761         run_lock->lock("MWindow::run");
2762         gui->run_window();
2763         stop_playback(1);
2764
2765         brender_lock->lock("MWindow::run 1");
2766         delete brender;         brender = 0;
2767         brender_lock->unlock();
2768
2769         interrupt_indexes();
2770         clean_indexes();
2771         save_defaults();
2772         run_lock->unlock();
2773 }
2774
2775 void MWindow::show_vwindow()
2776 {
2777         int total_running = 0;
2778         session->show_vwindow = 1;
2779
2780 //printf("MWindow::show_vwindow %d %d\n", __LINE__, vwindows.size());
2781 // Raise all windows which are visible
2782         for(int j = 0; j < vwindows.size(); j++) {
2783                 VWindow *vwindow = vwindows[j];
2784                 if( !vwindow->is_running() ) continue;
2785                 vwindow->gui->lock_window("MWindow::show_vwindow");
2786                 vwindow->gui->show_window(0);
2787                 vwindow->gui->raise_window();
2788                 vwindow->gui->flush();
2789                 vwindow->gui->unlock_window();
2790                 total_running++;
2791         }
2792
2793 // If no windows visible
2794         if(!total_running)
2795         {
2796                 get_viewer(1, DEFAULT_VWINDOW);
2797         }
2798
2799         gui->mainmenu->show_vwindow->set_checked(1);
2800 }
2801
2802 void MWindow::show_awindow()
2803 {
2804         session->show_awindow = 1;
2805         awindow->gui->lock_window("MWindow::show_awindow");
2806         awindow->gui->show_window();
2807         awindow->gui->raise_window();
2808         awindow->gui->flush();
2809         awindow->gui->unlock_window();
2810         gui->mainmenu->show_awindow->set_checked(1);
2811 }
2812
2813 char *MWindow::get_cwindow_display()
2814 {
2815         char *x11_host = screens < 2 || session->window_config == 0 ?
2816                 session->a_x11_host : session->b_x11_host;
2817         return *x11_host ? x11_host : 0;
2818 }
2819
2820 void MWindow::show_cwindow()
2821 {
2822         session->show_cwindow = 1;
2823         cwindow->show_window();
2824         gui->mainmenu->show_cwindow->set_checked(1);
2825 }
2826
2827 void MWindow::show_gwindow()
2828 {
2829         session->show_gwindow = 1;
2830
2831         gwindow->gui->lock_window("MWindow::show_gwindow");
2832         gwindow->gui->show_window();
2833         gwindow->gui->raise_window();
2834         gwindow->gui->flush();
2835         gwindow->gui->unlock_window();
2836
2837         gui->mainmenu->show_gwindow->set_checked(1);
2838 }
2839 void MWindow::hide_gwindow()
2840 {
2841         session->show_gwindow = 0;
2842
2843         gwindow->gui->lock_window("MWindow::show_gwindow");
2844         gwindow->gui->hide_window();
2845         gwindow->gui->unlock_window();
2846 }
2847
2848 void MWindow::show_lwindow()
2849 {
2850         session->show_lwindow = 1;
2851         lwindow->gui->lock_window("MWindow::show_lwindow");
2852         lwindow->gui->show_window();
2853         lwindow->gui->raise_window();
2854         lwindow->gui->flush();
2855         lwindow->gui->unlock_window();
2856         gui->mainmenu->show_lwindow->set_checked(1);
2857 }
2858
2859 void MWindow::restore_windows()
2860 {
2861         if( !session->show_vwindow ) {
2862                 for( int i=0, n=vwindows.size(); i<n; ++i ) {
2863                         VWindow *vwindow = vwindows[i];
2864                         if( !vwindow || !vwindow->is_running() ) continue;
2865                         vwindow->gui->lock_window("MWindow::restore_windows");
2866                         vwindow->gui->close(1);
2867                         vwindow->gui->unlock_window();
2868                 }
2869         }
2870         else
2871                 show_vwindow();
2872
2873         if( !session->show_awindow && !awindow->gui->is_hidden() ) {
2874                 awindow->gui->lock_window("MWindow::restore_windows");
2875                 awindow->gui->close_event();
2876                 awindow->gui->unlock_window();
2877         }
2878         else if( session->show_awindow && awindow->gui->is_hidden() )
2879                 show_awindow();
2880
2881         if( !session->show_cwindow && !cwindow->gui->is_hidden() ) {
2882                 cwindow->gui->lock_window("MWindow::restore_windows");
2883                 cwindow->hide_window();
2884                 cwindow->gui->unlock_window();
2885         }
2886         else if( session->show_cwindow && cwindow->gui->is_hidden() )
2887                 cwindow->show_window();
2888
2889         if( !session->show_gwindow && !gwindow->gui->is_hidden() ) {
2890                 gwindow->gui->lock_window("MWindow::restore_windows");
2891                 gwindow->gui->close_event();
2892                 gwindow->gui->unlock_window();
2893         }
2894         else if( session->show_gwindow && gwindow->gui->is_hidden() )
2895                 show_gwindow();
2896
2897         if( !session->show_lwindow && !lwindow->gui->is_hidden() ) {
2898                 lwindow->gui->lock_window("MWindow::restore_windows");
2899                 lwindow->gui->close_event();
2900                 lwindow->gui->unlock_window();
2901         }
2902         else if( session->show_lwindow && lwindow->gui->is_hidden() )
2903                 show_lwindow();
2904 }
2905
2906 int MWindow::tile_windows(int window_config)
2907 {
2908         int need_reload = 0;
2909         int play_config = window_config==0 ? 0 : 1;
2910         edl->session->playback_config->load_defaults(defaults, play_config);
2911         session->default_window_positions(window_config);
2912         if( screens == 1 ) {
2913                 gui->default_positions();
2914                 sync_parameters(CHANGE_ALL);
2915         }
2916         else
2917                 need_reload = 1;
2918         return need_reload;
2919 }
2920
2921 void MWindow::toggle_loop_playback()
2922 {
2923         edl->local_session->loop_playback = !edl->local_session->loop_playback;
2924         set_loop_boundaries();
2925         save_backup();
2926
2927         gui->draw_overlays(1);
2928         sync_parameters(CHANGE_PARAMS);
2929 }
2930
2931 void MWindow::set_screens(int value)
2932 {
2933         screens = value;
2934 }
2935
2936 void MWindow::set_auto_keyframes(int value, int lock_mwindow, int lock_cwindow)
2937 {
2938         if(lock_mwindow) gui->lock_window("MWindow::set_auto_keyframes");
2939         edl->session->auto_keyframes = value;
2940         gui->mbuttons->edit_panel->keyframe->update(value);
2941         gui->flush();
2942         if(lock_mwindow) gui->unlock_window();
2943
2944         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_auto_keyframes");
2945         cwindow->gui->edit_panel->keyframe->update(value);
2946         cwindow->gui->flush();
2947         if(lock_cwindow) cwindow->gui->unlock_window();
2948 }
2949
2950 void MWindow::set_auto_visibility(Autos *autos, int value)
2951 {
2952         if( autos->type == Autos::AUTOMATION_TYPE_PLUGIN )
2953                 edl->session->auto_conf->plugins = value;
2954         else if( autos->autoidx >= 0 )
2955                 edl->session->auto_conf->autos[autos->autoidx] = value;
2956         else
2957                 return;
2958
2959         gui->update(0, 1, 0, 0, 0, 0, 0);
2960         gui->mainmenu->update_toggles(1);
2961         gui->unlock_window();
2962         gwindow->gui->update_toggles(1);
2963         gui->lock_window("MWindow::set_auto_visibility");
2964 }
2965
2966 void MWindow::set_keyframe_type(int mode)
2967 {
2968         gui->lock_window("MWindow::set_keyframe_type");
2969         edl->local_session->floatauto_type = mode;
2970         gui->mainmenu->update_toggles(0);
2971         gui->unlock_window();
2972 }
2973
2974 int MWindow::set_editing_mode(int new_editing_mode, int lock_mwindow, int lock_cwindow)
2975 {
2976         if(lock_mwindow) gui->lock_window("MWindow::set_editing_mode");
2977         edl->session->editing_mode = new_editing_mode;
2978         gui->mbuttons->edit_panel->editing_mode = edl->session->editing_mode;
2979         gui->mbuttons->edit_panel->update();
2980         gui->set_editing_mode(1);
2981         if(lock_mwindow) gui->unlock_window();
2982
2983
2984         if(lock_cwindow) cwindow->gui->lock_window("MWindow::set_editing_mode");
2985         cwindow->gui->edit_panel->update();
2986         cwindow->gui->edit_panel->editing_mode = edl->session->editing_mode;
2987         if(lock_cwindow) cwindow->gui->unlock_window();
2988         return 0;
2989 }
2990
2991 void MWindow::toggle_editing_mode()
2992 {
2993         int mode = edl->session->editing_mode;
2994         if( mode == EDITING_ARROW )
2995                 set_editing_mode(EDITING_IBEAM, 0, 1);
2996         else
2997                 set_editing_mode(EDITING_ARROW, 0, 1);
2998 }
2999
3000 void MWindow::toggle_camera_xyz()
3001 {
3002         gwindow->gui->lock_window("MWindow::toggle_camera_xyz");
3003         gwindow->gui->toggle_camera_xyz();
3004         gwindow->gui->unlock_window();
3005 }
3006
3007 void MWindow::toggle_projector_xyz()
3008 {
3009         gwindow->gui->lock_window("MWindow::toggle_projector_xyz");
3010         gwindow->gui->toggle_projector_xyz();
3011         gwindow->gui->unlock_window();
3012 }
3013
3014 void MWindow::set_labels_follow_edits(int value)
3015 {
3016         gui->lock_window("MWindow::set_labels_follow_edits");
3017         edl->session->labels_follow_edits = value;
3018         gui->mbuttons->edit_panel->locklabels->update(value);
3019         gui->mainmenu->labels_follow_edits->set_checked(value);
3020         gui->flush();
3021         gui->unlock_window();
3022 }
3023
3024 void MWindow::sync_parameters(int change_type)
3025 {
3026         if( in_destructor ) return;
3027
3028 // Sync engines which are playing back
3029         if(cwindow->playback_engine->is_playing_back)
3030         {
3031                 if(change_type == CHANGE_PARAMS)
3032                 {
3033 // TODO: block keyframes until synchronization is done
3034                         cwindow->playback_engine->sync_parameters(edl);
3035                 }
3036                 else
3037 // Stop and restart
3038                 {
3039                         int command = cwindow->playback_engine->command->command;
3040                         cwindow->playback_engine->que->send_command(STOP,
3041                                 CHANGE_NONE,
3042                                 0,
3043                                 0);
3044 // Waiting for tracking to finish would make the restart position more
3045 // accurate but it can't lock the window to stop tracking for some reason.
3046 // Not waiting for tracking gives a faster response but restart position is
3047 // only as accurate as the last tracking update.
3048                         cwindow->playback_engine->interrupt_playback(0);
3049                         cwindow->playback_engine->que->send_command(command,
3050                                         change_type,
3051                                         edl,
3052                                         1,
3053                                         0);
3054                 }
3055         }
3056         else
3057         {
3058                 cwindow->refresh_frame(change_type);
3059         }
3060 }
3061
3062 void MWindow::age_caches()
3063 {
3064 // printf("MWindow::age_caches %d %lld %lld %lld %lld\n",
3065 // __LINE__,
3066 // preferences->cache_size,
3067 // audio_cache->get_memory_usage(1),
3068 // video_cache->get_memory_usage(1),
3069 // frame_cache->get_memory_usage(),
3070 // wave_cache->get_memory_usage(),
3071 // memory_usage);
3072         frame_cache->age_cache(512);
3073         wave_cache->age_cache(8192);
3074
3075         int64_t memory_usage;
3076         int64_t prev_memory_usage = 0;
3077         int result = 0;
3078         int64_t video_size = (int64_t)(preferences->cache_size * 0.80);
3079         while( !result && prev_memory_usage !=
3080                 (memory_usage=video_cache->get_memory_usage(1)) &&
3081                 memory_usage > video_size ) {
3082                 video_cache->delete_oldest();
3083                 prev_memory_usage = memory_usage;
3084         }
3085
3086         prev_memory_usage = 0;
3087         result = 0;
3088         int64_t audio_size = (int64_t)(preferences->cache_size * 0.20);
3089         while( !result && prev_memory_usage !=
3090                 (memory_usage=audio_cache->get_memory_usage(1)) &&
3091                 memory_usage > audio_size ) {
3092                 audio_cache->delete_oldest();
3093                 prev_memory_usage = memory_usage;
3094         }
3095 }
3096
3097 void MWindow::reset_android_remote()
3098 {
3099         gui->use_android_remote(preferences->android_remote);
3100 }
3101
3102
3103 void MWindow::show_keyframe_gui(Plugin *plugin)
3104 {
3105         keyframe_gui_lock->lock("MWindow::show_keyframe_gui");
3106 // Find existing thread
3107         for(int i = 0; i < keyframe_threads->size(); i++)
3108         {
3109                 if(keyframe_threads->get(i)->plugin == plugin)
3110                 {
3111                         keyframe_threads->get(i)->start_window(plugin, 0);
3112                         keyframe_gui_lock->unlock();
3113                         return;
3114                 }
3115         }
3116
3117 // Find unused thread
3118         for(int i = 0; i < keyframe_threads->size(); i++)
3119         {
3120                 if(!keyframe_threads->get(i)->plugin)
3121                 {
3122                         keyframe_threads->get(i)->start_window(plugin, 0);
3123                         keyframe_gui_lock->unlock();
3124                         return;
3125                 }
3126         }
3127
3128 // Create new thread
3129         KeyFrameThread *thread = new KeyFrameThread(this);
3130         keyframe_threads->append(thread);
3131         thread->start_window(plugin, 0);
3132
3133         keyframe_gui_lock->unlock();
3134 }
3135
3136
3137
3138
3139
3140 void MWindow::show_plugin(Plugin *plugin)
3141 {
3142         int done = 0;
3143
3144 SET_TRACE
3145 // Remove previously deleted plugin GUIs
3146         dead_plugin_lock->lock("MWindow::show_plugin");
3147         dead_plugins->remove_all_objects();
3148         dead_plugin_lock->unlock();
3149
3150 //printf("MWindow::show_plugin %d\n", __LINE__);
3151 SET_TRACE
3152
3153
3154         plugin_gui_lock->lock("MWindow::show_plugin");
3155         for(int i = 0; i < plugin_guis->total; i++)
3156         {
3157 // Pointer comparison
3158                 if(plugin_guis->get(i)->plugin == plugin)
3159                 {
3160                         plugin_guis->get(i)->raise_window();
3161                         done = 1;
3162                         break;
3163                 }
3164         }
3165 SET_TRACE
3166
3167 //printf("MWindow::show_plugin 1\n");
3168         if( !done && !plugin->track ) {
3169                 printf("MWindow::show_plugin track not defined.\n");
3170                 done = 1;
3171         }
3172         if( !done ) {
3173                 PluginServer *server = scan_plugindb(plugin->title,
3174                         plugin->track->data_type);
3175
3176 //printf("MWindow::show_plugin %p %d\n", server, server->uses_gui);
3177                 if(server && server->uses_gui)
3178                 {
3179                         PluginServer *gui = new PluginServer(*server);
3180                         plugin_guis->append(gui);
3181 // Needs mwindow to do GUI
3182                         gui->set_mwindow(this);
3183                         gui->open_plugin(0, preferences, edl, plugin);
3184                         plugin->show = 1;
3185                         gui->show_gui();
3186                 }
3187         }
3188         plugin_gui_lock->unlock();
3189 //printf("MWindow::show_plugin %d\n", __LINE__);
3190 SET_TRACE
3191 //sleep(1);
3192 //printf("MWindow::show_plugin 2\n");
3193 }
3194
3195 void MWindow::hide_plugin(Plugin *plugin, int lock)
3196 {
3197         plugin->show = 0;
3198 // Update the toggle
3199         gui->lock_window("MWindow::hide_plugin");
3200         gui->update(0, 1, 0, 0, 0, 0, 0);
3201         gui->unlock_window();
3202
3203         if(lock) plugin_gui_lock->lock("MWindow::hide_plugin");
3204         for(int i = 0; i < plugin_guis->total; i++)
3205         {
3206                 if(plugin_guis->get(i)->plugin == plugin)
3207                 {
3208                         PluginServer *ptr = plugin_guis->get(i);
3209                         plugin_guis->remove(ptr);
3210                         if(lock) plugin_gui_lock->unlock();
3211 // Last command executed in client side close
3212 // Schedule for deletion
3213                         ptr->hide_gui();
3214                         delete_plugin(ptr);
3215 //sleep(1);
3216                         return;
3217                 }
3218         }
3219         if(lock) plugin_gui_lock->unlock();
3220 }
3221
3222 void MWindow::delete_plugin(PluginServer *plugin)
3223 {
3224         dead_plugin_lock->lock("MWindow::delete_plugin");
3225         dead_plugins->append(plugin);
3226         dead_plugin_lock->unlock();
3227 }
3228
3229 void MWindow::hide_plugins()
3230 {
3231         plugin_gui_lock->lock("MWindow::hide_plugins 1");
3232         while(plugin_guis->size())
3233         {
3234                 PluginServer *ptr = plugin_guis->get(0);
3235                 plugin_guis->remove(ptr);
3236                 plugin_gui_lock->unlock();
3237 // Last command executed in client side close
3238 // Schedule for deletion
3239                 ptr->hide_gui();
3240                 delete_plugin(ptr);
3241                 plugin_gui_lock->lock("MWindow::hide_plugins 2");
3242         }
3243         plugin_gui_lock->unlock();
3244
3245         hide_keyframe_guis();
3246 }
3247
3248 void MWindow::hide_keyframe_guis()
3249 {
3250         keyframe_gui_lock->lock("MWindow::hide_keyframe_guis");
3251         for(int i = 0; i < keyframe_threads->size(); i++)
3252         {
3253                 keyframe_threads->get(i)->close_window();
3254         }
3255         keyframe_gui_lock->unlock();
3256 }
3257
3258 void MWindow::hide_keyframe_gui(Plugin *plugin)
3259 {
3260         keyframe_gui_lock->lock("MWindow::hide_keyframe_gui");
3261         for(int i = 0; i < keyframe_threads->size(); i++)
3262         {
3263                 if(keyframe_threads->get(i)->plugin == plugin)
3264                 {
3265                         keyframe_threads->get(i)->close_window();
3266                         break;
3267                 }
3268         }
3269         keyframe_gui_lock->unlock();
3270 }
3271
3272 void MWindow::update_keyframe_guis()
3273 {
3274 // Send new configuration to keyframe GUI's
3275         keyframe_gui_lock->lock("MWindow::update_keyframe_guis");
3276         for(int i = 0; i < keyframe_threads->size(); i++)
3277         {
3278                 KeyFrameThread *ptr = keyframe_threads->get(i);
3279                 if(edl->tracks->plugin_exists(ptr->plugin))
3280                         ptr->update_gui(1);
3281                 else
3282                 {
3283                         ptr->close_window();
3284                 }
3285         }
3286         keyframe_gui_lock->unlock();
3287 }
3288
3289 void MWindow::update_plugin_guis(int do_keyframe_guis)
3290 {
3291 // Send new configuration to plugin GUI's
3292         plugin_gui_lock->lock("MWindow::update_plugin_guis");
3293
3294         for(int i = 0; i < plugin_guis->size(); i++)
3295         {
3296                 PluginServer *ptr = plugin_guis->get(i);
3297                 if(edl->tracks->plugin_exists(ptr->plugin))
3298                         ptr->update_gui();
3299                 else
3300                 {
3301 // Schedule for deletion if no plugin
3302                         plugin_guis->remove_number(i);
3303                         i--;
3304
3305                         ptr->hide_gui();
3306                         delete_plugin(ptr);
3307                 }
3308         }
3309
3310
3311 // Change plugin variable if not visible
3312         Track *track = edl->tracks->first;
3313         while(track)
3314         {
3315                 for(int i = 0; i < track->plugin_set.size(); i++)
3316                 {
3317                         Plugin *plugin = (Plugin*)track->plugin_set[i]->first;
3318                         while(plugin)
3319                         {
3320                                 int got_it = 0;
3321                                 for(int i = 0; i < plugin_guis->size(); i++)
3322                                 {
3323                                         PluginServer *server = plugin_guis->get(i);
3324                                         if(server->plugin == plugin)
3325                                         {
3326                                                 got_it = 1;
3327                                                 break;
3328                                         }
3329                                 }
3330
3331                                 if(!got_it) plugin->show = 0;
3332
3333                                 plugin = (Plugin*)plugin->next;
3334                         }
3335                 }
3336
3337                 track = track->next;
3338         }
3339
3340         plugin_gui_lock->unlock();
3341
3342
3343         if(do_keyframe_guis) update_keyframe_guis();
3344 }
3345
3346 int MWindow::plugin_gui_open(Plugin *plugin)
3347 {
3348         int result = 0;
3349         plugin_gui_lock->lock("MWindow::plugin_gui_open");
3350         for(int i = 0; i < plugin_guis->total; i++)
3351         {
3352                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3353                 {
3354                         result = 1;
3355                         break;
3356                 }
3357         }
3358         plugin_gui_lock->unlock();
3359         return result;
3360 }
3361
3362 void MWindow::render_plugin_gui(void *data, Plugin *plugin)
3363 {
3364         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3365         for(int i = 0; i < plugin_guis->total; i++)
3366         {
3367                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3368                 {
3369                         plugin_guis->get(i)->render_gui(data);
3370                         break;
3371                 }
3372         }
3373         plugin_gui_lock->unlock();
3374 }
3375
3376 void MWindow::render_plugin_gui(void *data, int size, Plugin *plugin)
3377 {
3378         plugin_gui_lock->lock("MWindow::render_plugin_gui");
3379         for(int i = 0; i < plugin_guis->total; i++)
3380         {
3381                 if(plugin_guis->get(i)->plugin->identical_location(plugin))
3382                 {
3383                         plugin_guis->get(i)->render_gui(data, size);
3384                         break;
3385                 }
3386         }
3387         plugin_gui_lock->unlock();
3388 }
3389
3390
3391 void MWindow::update_plugin_states()
3392 {
3393         plugin_gui_lock->lock("MWindow::update_plugin_states");
3394         for(int i = 0; i < plugin_guis->total; i++)
3395         {
3396                 int result = 0;
3397 // Get a plugin GUI
3398                 Plugin *src_plugin = plugin_guis->get(i)->plugin;
3399                 PluginServer *src_plugingui = plugin_guis->get(i);
3400
3401 // Search for plugin in EDL.  Only the master EDL shows plugin GUIs.
3402                 for(Track *track = edl->tracks->first;
3403                         track && !result;
3404                         track = track->next)
3405                 {
3406                         for(int j = 0;
3407                                 j < track->plugin_set.total && !result;
3408                                 j++)
3409                         {
3410                                 PluginSet *plugin_set = track->plugin_set[j];
3411                                 for(Plugin *plugin = (Plugin*)plugin_set->first;
3412                                         plugin && !result;
3413                                         plugin = (Plugin*)plugin->next)
3414                                 {
3415                                         if(plugin == src_plugin &&
3416                                                 !strcmp(plugin->title, src_plugingui->title)) result = 1;
3417                                 }
3418                         }
3419                 }
3420
3421
3422 // Doesn't exist anymore
3423                 if(!result)
3424                 {
3425                         hide_plugin(src_plugin, 0);
3426                         i--;
3427                 }
3428         }
3429         plugin_gui_lock->unlock();
3430 }
3431
3432
3433 void MWindow::update_plugin_titles()
3434 {
3435         for(int i = 0; i < plugin_guis->total; i++)
3436         {
3437                 plugin_guis->get(i)->update_title();
3438         }
3439 }
3440
3441 int MWindow::asset_to_edl(EDL *new_edl,
3442         Asset *new_asset,
3443         RecordLabels *labels)
3444 {
3445 const int debug = 0;
3446 if(debug) printf("MWindow::asset_to_edl %d new_asset->layers=%d\n",
3447 __LINE__,
3448 new_asset->layers);
3449 // Keep frame rate, sample rate, and output size unchanged.
3450 // These parameters would revert the project if VWindow displayed an asset
3451 // of different size than the project.
3452         if(new_asset->video_data)
3453         {
3454                 new_edl->session->video_tracks = new_asset->layers;
3455         }
3456         else
3457                 new_edl->session->video_tracks = 0;
3458
3459 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3460
3461
3462
3463
3464
3465         if(new_asset->audio_data)
3466         {
3467                 new_edl->session->audio_tracks = new_asset->channels;
3468         }
3469         else
3470                 new_edl->session->audio_tracks = 0;
3471 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3472
3473 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3474         new_edl->create_default_tracks();
3475 //printf("MWindow::asset_to_edl 2 %d %d\n", new_edl->session->video_tracks, new_edl->session->audio_tracks);
3476 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3477
3478
3479
3480 //printf("MWindow::asset_to_edl 3\n");
3481         new_edl->insert_asset(new_asset,
3482                 0,
3483                 0,
3484                 0,
3485                 labels);
3486 //printf("MWindow::asset_to_edl 3\n");
3487 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3488
3489 // Align cursor on frames:: clip the new_edl to the minimum of the last joint frame.
3490         if(edl->session->cursor_on_frames)
3491         {
3492                 double length = new_edl->tracks->total_length();
3493                 double edl_length = new_edl->tracks->total_length_framealigned(edl->session->frame_rate);
3494                 new_edl->tracks->clear(length, edl_length, 1, 1);
3495         }
3496
3497
3498
3499
3500         char string[BCTEXTLEN];
3501         FileSystem fs;
3502         fs.extract_name(string, new_asset->path);
3503 //printf("MWindow::asset_to_edl 3\n");
3504
3505         strcpy(new_edl->local_session->clip_title, string);
3506 //printf("MWindow::asset_to_edl 4 %s\n", string);
3507 if(debug) printf("MWindow::asset_to_edl %d\n", __LINE__);
3508
3509         return 0;
3510 }
3511
3512
3513 // Reset everything after a load.
3514 void MWindow::update_project(int load_mode)
3515 {
3516         const int debug = 0;
3517
3518         if(debug) PRINT_TRACE
3519         edl->tracks->update_y_pixels(theme);
3520         session->update_clip_number();
3521
3522         if(debug) PRINT_TRACE
3523
3524         if( load_mode == LOADMODE_REPLACE ||
3525             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3526                 delete gui->keyvalue_popup;
3527                 gui->keyvalue_popup = 0;
3528                 gui->load_panes();
3529         }
3530
3531         gui->update(1, 1, 1, 1, 1, 1, 1);
3532         if(debug) PRINT_TRACE
3533         gui->unlock_window();
3534         init_brender();
3535
3536         cwindow->gui->lock_window("MWindow::update_project 1");
3537         cwindow->update(0, 0, 1, 1, 1);
3538         cwindow->gui->unlock_window();
3539
3540         if(debug) PRINT_TRACE
3541
3542 // Close all the vwindows
3543         if( load_mode == LOADMODE_REPLACE ||
3544             load_mode == LOADMODE_REPLACE_CONCATENATE ) {
3545                 if(debug) PRINT_TRACE
3546                 int first_vwindow = 0;
3547                 if(session->show_vwindow) first_vwindow = 1;
3548 // Change visible windows to no source
3549                 for(int i = 0; i < first_vwindow && i < vwindows.size(); i++) {
3550                         VWindow *vwindow = vwindows[i];
3551                         if( !vwindow->is_running() ) continue;
3552                         vwindow->change_source(-1);
3553                 }
3554
3555 // Close remaining windows
3556                 for(int i = first_vwindow; i < vwindows.size(); i++) {
3557                         VWindow *vwindow = vwindows[i];
3558                         if( !vwindow->is_running() ) continue;
3559                         vwindow->close_window();
3560                 }
3561                 for( int i=0; i<edl->vwindow_edls.size(); ++i ) {
3562                         VWindow *vwindow = get_viewer(1, -1);
3563                         vwindow->change_source(i);
3564                 }
3565                 if(debug) PRINT_TRACE
3566                 select_zwindow(0);
3567                 close_mixers(0);
3568
3569                 for( int i=0; i<edl->mixers.size(); ++i ) {
3570                         Mixer *mixer = edl->mixers[i];
3571                         ZWindow *zwindow = get_mixer(mixer);
3572                         zwindow->set_title(mixer->title);
3573                         zwindow->start();
3574                 }
3575         }
3576         update_vwindow();
3577
3578         if(debug) PRINT_TRACE
3579         cwindow->gui->lock_window("MWindow::update_project 2");
3580         cwindow->gui->timebar->update(0);
3581         cwindow->gui->unlock_window();
3582
3583         if(debug) PRINT_TRACE
3584         cwindow->refresh_frame(CHANGE_ALL);
3585
3586         awindow->gui->async_update_assets();
3587         if(debug) PRINT_TRACE
3588
3589         gui->lock_window("MWindow::update_project");
3590         gui->update_mixers(0, 0);
3591         gui->flush();
3592         if(debug) PRINT_TRACE
3593 }
3594
3595 void MWindow::update_vwindow()
3596 {
3597         for( int i=0; i<vwindows.size(); ++i ) {
3598                 VWindow *vwindow = vwindows[i];
3599                 if( vwindow->is_running() ) {
3600                         vwindow->gui->lock_window("MWindow::update_vwindow");
3601                         vwindow->update(1);
3602                         vwindow->gui->unlock_window();
3603                 }
3604         }
3605 }
3606
3607 void MWindow::remove_indexfile(Indexable *indexable)
3608 {
3609         if( !indexable->is_asset ) return;
3610         Asset *asset = (Asset *)indexable;
3611 // Erase file
3612         IndexFile::delete_index(preferences, asset, ".toc");
3613         IndexFile::delete_index(preferences, asset, ".idx");
3614         IndexFile::delete_index(preferences, asset, ".mkr");
3615 }
3616
3617 void MWindow::rebuild_indices()
3618 {
3619         for(int i = 0; i < session->drag_assets->total; i++)
3620         {
3621                 Indexable *indexable = session->drag_assets->get(i);
3622 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
3623                 remove_indexfile(indexable);
3624 // Schedule index build
3625                 IndexState *index_state = indexable->index_state;
3626                 index_state->index_status = INDEX_NOTTESTED;
3627                 if( indexable->is_asset ) {
3628                         Asset *asset = (Asset *)indexable;
3629                         if( asset->format != FILE_PCM ) {
3630                                 asset->format = FILE_UNKNOWN;
3631                                 asset->reset_audio();
3632                         }
3633                         asset->reset_video();
3634                         remove_asset_from_caches(asset);
3635 //                      File file; // re-probe the asset
3636 //                      file.open_file(preferences, asset, 1, 0);
3637                 }
3638                 mainindexes->add_next_asset(0, indexable);
3639         }
3640         mainindexes->start_build();
3641 }
3642
3643
3644 void MWindow::save_backup()
3645 {
3646         FileXML file;
3647         edl->optimize();
3648         edl->set_path(session->filename);
3649         char backup_path[BCTEXTLEN], backup_path1[BCTEXTLEN];
3650         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3651                 File::get_config_path(), BACKUP_FILE);
3652         snprintf(backup_path1, sizeof(backup_path1), "%s/%s",
3653                 File::get_config_path(), BACKUP_FILE1);
3654         rename(backup_path, backup_path1);
3655         edl->save_xml(&file, backup_path);
3656         file.terminate_string();
3657         FileSystem fs;
3658         fs.complete_path(backup_path);
3659
3660         if(file.write_to_file(backup_path))
3661         {
3662                 char string2[256];
3663                 sprintf(string2, _("Couldn't open %s for writing."), backup_path);
3664                 gui->show_message(string2);
3665         }
3666 }
3667
3668 void MWindow::load_backup()
3669 {
3670         ArrayList<char*> path_list;
3671         path_list.set_array_delete();
3672         char *out_path;
3673         char backup_path[BCTEXTLEN];
3674         snprintf(backup_path, sizeof(backup_path), "%s/%s",
3675                 File::get_config_path(), BACKUP_FILE);
3676         FileSystem fs;
3677         fs.complete_path(backup_path);
3678
3679         path_list.append(out_path = new char[strlen(backup_path) + 1]);
3680         strcpy(out_path, backup_path);
3681
3682         load_filenames(&path_list, LOADMODE_REPLACE, 0);
3683         edl->local_session->clip_title[0] = 0;
3684 // This is unique to backups since the path of the backup is different than the
3685 // path of the project.
3686         set_filename(edl->path);
3687         path_list.remove_all_objects();
3688         save_backup();
3689 }
3690
3691
3692 void MWindow::save_undo_data()
3693 {
3694         undo->update_undo_before();
3695         undo->update_undo_after(_("perpetual session"), LOAD_ALL);
3696         char perpetual_path[BCTEXTLEN];
3697         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
3698                 File::get_config_path(), PERPETUAL_FILE);
3699         FILE *fp = fopen(perpetual_path,"w");
3700         if( !fp ) return;
3701         undo->save(fp);
3702         fclose(fp);
3703 }
3704
3705 void MWindow::load_undo_data()
3706 {
3707         char perpetual_path[BCTEXTLEN];
3708         snprintf(perpetual_path, sizeof(perpetual_path), "%s/%s",
3709                 File::get_config_path(), PERPETUAL_FILE);
3710         FILE *fp = fopen(perpetual_path,"r");
3711         if( !fp ) return;
3712         undo->load(fp);
3713         fclose(fp);
3714 }
3715
3716
3717 int MWindow::copy_target(const char *path, const char *target)
3718 {
3719         int ifd = ::open(path, O_RDONLY);
3720         if( ifd < 0 ) {
3721                 eprintf("Cannot open asset: %s", path);
3722                 return 1;
3723         }
3724         int ret = 0;
3725         int ofd = ::open(target, O_CREAT+O_TRUNC+O_WRONLY, 0777);
3726         if( ofd >= 0 ) {
3727                 struct stat st;
3728                 int64_t total_bytes = !fstat(ifd, &st) ? st.st_size : 0;
3729                 char progress_title[BCTEXTLEN];
3730                 sprintf(progress_title, _("Copying: %s\n"), target);
3731                 BC_ProgressBox progress(-1, -1, progress_title, total_bytes);
3732
3733                 int64_t count = 0, len = -1;
3734                 int bfrsz = 0x100000;
3735                 uint8_t *bfr = new uint8_t[bfrsz];
3736                 while( (len=::read(ifd, bfr, bfrsz)) > 0 ) {
3737                         if( len != ::write(ofd, bfr, len) ) {
3738                                 eprintf("Error writing: %s", target);
3739                                 break;
3740                         }
3741                         if( progress.is_cancelled() ) {
3742                                 ret = 1;
3743                                 break;
3744                         }
3745                         progress.update(count += len, 1);
3746                 }
3747                 delete [] bfr;
3748                 ::close(ofd);
3749
3750                 progress.stop_progress();
3751                 if( len < 0 ) {
3752                         eprintf("Error reading: %s", path);
3753                         ret = 1;
3754                 }
3755         }
3756         else
3757                 eprintf("Cannot create asset target: %s", target);
3758         ::close(ifd);
3759         return ret;
3760 }
3761
3762 int MWindow::link_target(const char *real_path, const char *link_path, int relative)
3763 {
3764         char target[BCTEXTLEN];
3765         if( relative ) {
3766                 const char *bp = real_path, *cp = bp;
3767                 const char *lp = link_path, *np = lp;
3768                 char *tp = target, *ep = tp+sizeof(target)-1, lch;
3769                 while( *lp && *bp && (lch=*lp++) == *bp++ ) {
3770                         if( lch == '/' ) { np = lp;  cp = bp; }
3771                 }
3772                 while( tp<ep && *np ) {
3773                         if( *np++ != '/' ) continue;
3774                         *tp++ = '.';  *tp++ = '.';  *tp++ = '/';
3775                 }
3776                 while( tp<ep && *cp ) *tp++ = *cp++;
3777                 *tp = 0;
3778         }
3779         else
3780                 strcpy(target, real_path);
3781         if( symlink(target, link_path) ) {
3782                 eprintf("Cannot create symlink: %s", link_path);
3783                 return 1;
3784         }
3785         return 0;
3786 }
3787
3788 void MWindow::save_project(const char *dir, int save_mode, int overwrite, int reload)
3789 {
3790         char dir_path[BCTEXTLEN];
3791         strcpy(dir_path, dir);
3792         FileSystem fs;
3793         fs.complete_path(dir_path);
3794
3795         struct stat st;
3796         if( !stat(dir_path, &st) ) {
3797                 if( !S_ISDIR(st.st_mode) ) {
3798                         eprintf("Path exists and is not a directory\n%s", dir_path);
3799                         return;
3800                 }
3801         }
3802         else {
3803                 if( mkdir(dir_path, S_IRWXU | S_IRWXG | S_IRWXO) ) {
3804                         eprintf("Cannot create directory\n%s", dir_path);
3805                         return;
3806                 }
3807         }
3808         char *real_dir = realpath(dir_path, 0);
3809         strcpy(dir_path, real_dir);
3810         free(real_dir);
3811
3812         EDL *save_edl = new EDL;
3813         save_edl->create_objects();
3814         save_edl->copy_all(edl);
3815
3816         char progress_title[BCTEXTLEN];
3817         sprintf(progress_title, _("Saving to %s:\n"), dir);
3818         int total_assets = save_edl->assets->total();
3819         MainProgressBar *progress = mainprogress->start_progress(progress_title, total_assets);
3820         int ret = 0;
3821         Asset *current = save_edl->assets->first;
3822         for( int i=0; !ret && current; ++i, current=NEXT ) {
3823                 char *path = current->path;
3824                 if( ::stat(path, &st) ) {
3825                         eprintf("Asset not found: %s", path);
3826                         continue;
3827                 }
3828                 char *real_path = realpath(path, 0);
3829                 const char *cp = strrchr(path, '/'), *bp = !cp ? path : cp+1;
3830                 char link_path[BCTEXTLEN];
3831                 snprintf(link_path, sizeof(link_path), "%s/%s", dir_path, bp);
3832                 int skip = 0;
3833                 if( strcmp(real_path, link_path) ) {
3834                         if( !::lstat(link_path, &st) ) {
3835                                 if( overwrite )
3836                                         ::remove(link_path);
3837                                 else
3838                                         skip = 1;
3839                         }
3840                 }
3841                 else {
3842                         eprintf("copy/link to self, skippped: %s", path);
3843                         skip = 1;
3844                 }
3845                 if( !skip ) {
3846                         if( save_mode == SAVE_PROJECT_COPY ) {
3847                                 if( copy_target(real_path, link_path) )
3848                                         ret = 1;
3849                         }
3850                         else {
3851                                 link_target(real_path, link_path,
3852                                         save_mode == SAVE_PROJECT_RELLINK ? 1 : 0);
3853                         }
3854                 }
3855                 free(real_path);
3856                 strcpy(path, link_path);
3857
3858                 if( progress->is_cancelled() ) break;
3859                 progress->update(i);
3860         }
3861
3862         progress->stop_progress();
3863         delete progress;
3864
3865         char *cp = strrchr(dir_path,'/');
3866         char *bp = cp ? cp+1 : dir_path;
3867         char filename[BCTEXTLEN];
3868         snprintf(filename, sizeof(filename), "%s/%s.xml", dir_path, bp);
3869         save_edl->set_path(filename);
3870         FileXML file;
3871         save_edl->save_xml(&file, filename);
3872         file.terminate_string();
3873
3874         if( !file.write_to_file(filename) ) {
3875                 char string[BCTEXTLEN];
3876                 sprintf(string, _("\"%s\" %dC written"), filename, (int)strlen(file.string()));
3877                 gui->lock_window("SaveProject::run 2");
3878                 gui->show_message(string);
3879                 gui->unlock_window();
3880                 gui->mainmenu->add_load(filename);
3881         }
3882         else
3883                 eprintf(_("Couldn't open %s."), filename);
3884
3885         save_edl->remove_user();
3886
3887         if( reload ) {
3888                 gui->lock_window("MWindow::save_project");
3889                 ArrayList<char*> filenames;
3890                 filenames.append(filename);
3891                 load_filenames(&filenames, LOADMODE_REPLACE);
3892                 gui->unlock_window();
3893         }
3894 }
3895
3896
3897 static inline int gcd(int m, int n)
3898 {
3899         int r;
3900         if( m < n ) { r = m;  m = n;  n = r; }
3901         while( (r = m % n) != 0 ) { m = n;  n = r; }
3902         return n;
3903 }
3904
3905 int MWindow::create_aspect_ratio(float &w, float &h, int width, int height)
3906 {
3907         w = 1;  h = 1;
3908         if(!width || !height) return 1;
3909         if( width == 720 && (height == 480 || height == 576) ) {
3910                 w = 4;  h = 3;  return 0; // for NTSC and PAL
3911         }
3912         double ar = (double)width / height;
3913 // square-ish pixels
3914         if( EQUIV(ar, 1.0000) ) return 0;
3915         if( EQUIV(ar, 1.3333) ) { w = 4;  h = 3;  return 0; }
3916         if( EQUIV(ar, 1.7777) ) { w = 16; h = 9;  return 0; }
3917         if( EQUIV(ar, 2.1111) ) { w = 19; h = 9;  return 0; }
3918         if( EQUIV(ar, 2.2222) ) { w = 20; h = 9;  return 0; }
3919         if( EQUIV(ar, 2.3333) ) { w = 21; h = 9;  return 0; }
3920         int ww = width, hh = height;
3921         // numerator, denominator must be under mx
3922         int mx = 255, n = gcd(ww, hh);
3923         if( n > 1 ) { ww /= n; hh /= n; }
3924         // search near height in case extra/missing lines
3925         if( ww >= mx || hh >= mx ) {
3926                 double err = height;  // +/- 2 percent height
3927                 for( int m=2*height/100, i=1; m>0; i=i>0 ? -i : (--m, -i+1) ) {
3928                         int iw = width, ih = height+i;
3929                         if( (n=gcd(iw, ih)) > 1 ) {
3930                                 int u = iw/n;  if( u >= mx ) continue;
3931                                 int v = ih/n;  if( v >= mx ) continue;
3932                                 double r = (double) u/v, er = fabs(ar-r);
3933                                 if( er >= err ) continue;
3934                                 err = er;  ww = u;  hh = v;
3935                         }
3936                 }
3937         }
3938
3939         w = ww;  h = hh;
3940         return 0;
3941 }
3942
3943 void MWindow::reset_caches()
3944 {
3945         frame_cache->remove_all();
3946         wave_cache->remove_all();
3947         audio_cache->remove_all();
3948         video_cache->remove_all();
3949         if( cwindow->playback_engine ) {
3950                 if( cwindow->playback_engine->audio_cache )
3951                         cwindow->playback_engine->audio_cache->remove_all();
3952                 if( cwindow->playback_engine->video_cache )
3953                         cwindow->playback_engine->video_cache->remove_all();
3954         }
3955         for(int i = 0; i < vwindows.size(); i++) {
3956                 VWindow *vwindow = vwindows[i];
3957                 if( !vwindow->is_running() ) continue;
3958                 if( !vwindow->playback_engine ) continue;
3959                 if( vwindow->playback_engine->audio_cache )
3960                         vwindow->playback_engine->audio_cache->remove_all();
3961                 if( vwindow->playback_engine->video_cache )
3962                         vwindow->playback_engine->video_cache->remove_all();
3963         }
3964 }
3965
3966 void MWindow::remove_asset_from_caches(Asset *asset)
3967 {
3968         frame_cache->remove_asset(asset);
3969         wave_cache->remove_asset(asset);
3970         audio_cache->delete_entry(asset);
3971         video_cache->delete_entry(asset);
3972         if( cwindow->playback_engine && cwindow->playback_engine->audio_cache )
3973                 cwindow->playback_engine->audio_cache->delete_entry(asset);
3974         if( cwindow->playback_engine && cwindow->playback_engine->video_cache )
3975                 cwindow->playback_engine->video_cache->delete_entry(asset);
3976         for(int i = 0; i < vwindows.size(); i++) {
3977                 VWindow *vwindow = vwindows[i];
3978                 if( !vwindow->is_running() ) continue;
3979                 if( !vwindow->playback_engine ) continue;
3980                 if( vwindow->playback_engine->audio_cache )
3981                         vwindow->playback_engine->audio_cache->delete_entry(asset);
3982                 if( vwindow->playback_engine->video_cache )
3983                         vwindow->playback_engine->video_cache->delete_entry(asset);
3984         }
3985 }
3986
3987
3988 void MWindow::remove_assets_from_project(int push_undo, int redraw,
3989                 ArrayList<Indexable*> *drag_assets, ArrayList<EDL*> *drag_clips)
3990 {
3991         for(int i = 0; i < drag_assets->total; i++) {
3992                 Indexable *indexable = drag_assets->get(i);
3993                 if(indexable->is_asset) remove_asset_from_caches((Asset*)indexable);
3994         }
3995
3996 // Remove from VWindow.
3997         for(int i = 0; i < session->drag_clips->total; i++) {
3998                 for(int j = 0; j < vwindows.size(); j++) {
3999                         VWindow *vwindow = vwindows[j];
4000                         if( !vwindow->is_running() ) continue;
4001                         if(session->drag_clips->get(i) == vwindow->get_edl()) {
4002                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 1");
4003                                 vwindow->delete_source(1, 1);
4004                                 vwindow->gui->unlock_window();
4005                         }
4006                 }
4007         }
4008
4009         for(int i = 0; i < drag_assets->size(); i++) {
4010                 for(int j = 0; j < vwindows.size(); j++) {
4011                         VWindow *vwindow = vwindows[j];
4012                         if( !vwindow->is_running() ) continue;
4013                         if(drag_assets->get(i) == vwindow->get_source()) {
4014                                 vwindow->gui->lock_window("MWindow::remove_assets_from_project 2");
4015                                 vwindow->delete_source(1, 1);
4016                                 vwindow->gui->unlock_window();
4017                         }
4018                 }
4019         }
4020
4021         for(int i = 0; i < drag_assets->size(); i++) {
4022                 Indexable *indexable = drag_assets->get(i);
4023                 remove_indexfile(indexable);
4024         }
4025
4026 //printf("MWindow::rebuild_indices 1 %s\n", indexable->path);
4027         if(push_undo) undo->update_undo_before();
4028         if(drag_assets) edl->remove_from_project(drag_assets);
4029         if(drag_clips) edl->remove_from_project(drag_clips);
4030         if(redraw) save_backup();
4031         if(push_undo) undo->update_undo_after(_("remove assets"), LOAD_ALL);
4032         if(redraw) {
4033                 restart_brender();
4034
4035                 gui->lock_window("MWindow::remove_assets_from_project 3");
4036                 gui->update(1, 1, 1, 1, 0, 1, 0);
4037                 gui->unlock_window();
4038
4039         // Removes from playback here
4040                 sync_parameters(CHANGE_ALL);
4041         }
4042
4043         awindow->gui->async_update_assets();
4044 }
4045
4046 void MWindow::remove_assets_from_disk()
4047 {
4048 // Remove from disk
4049         for(int i = 0; i < session->drag_assets->total; i++)
4050         {
4051                 remove(session->drag_assets->get(i)->path);
4052         }
4053
4054         remove_assets_from_project(1,
4055                 1,
4056                 session->drag_assets,
4057                 session->drag_clips);
4058 }
4059
4060 void MWindow::dump_plugins(FILE *fp)
4061 {
4062         if( !plugindb ) return;
4063         for(int i = 0; i < plugindb->total; i++)
4064         {
4065                 fprintf(fp, "type=%d audio=%d video=%d rt=%d multi=%d"
4066                         " synth=%d transition=%d theme=%d %s\n",
4067                         plugindb->get(i)->plugin_type,
4068                         plugindb->get(i)->audio,
4069                         plugindb->get(i)->video,
4070                         plugindb->get(i)->realtime,
4071                         plugindb->get(i)->multichannel,
4072                         plugindb->get(i)->get_synthesis(),
4073                         plugindb->get(i)->transition,
4074                         plugindb->get(i)->theme,
4075                         plugindb->get(i)->title);
4076         }
4077 }
4078
4079 void MWindow::dump_edl(FILE *fp)
4080 {
4081         if( !edl ) return;
4082         edl->dump(fp);
4083 }
4084
4085 void MWindow::dump_undo(FILE *fp)
4086 {
4087         if( !undo ) return;
4088         undo->dump(fp);
4089 }
4090
4091 void MWindow::dump_exe(FILE *fp)
4092 {
4093         char proc_path[BCTEXTLEN], exe_path[BCTEXTLEN];
4094         sprintf(proc_path, "/proc/%d/exe", (int)getpid());
4095
4096         int ret = -1, n = 100;
4097         for( int len; (len=readlink(proc_path, exe_path, sizeof(exe_path)))>0; --n ) {
4098                 exe_path[len] = 0;  strcpy(proc_path, exe_path);
4099                 ret = 0;
4100         }
4101         if( n < 0 || ret < 0 ) { fprintf(fp,"readlink: %m\n"); return; }
4102
4103         struct stat st;
4104         if( stat(proc_path,&st) ) { fprintf(fp,"stat: %m\n"); return; }
4105         fprintf(fp, "path: %s = %9jd bytes\n",proc_path,st.st_size);
4106         struct tm *tm = localtime(&st.st_mtime);
4107         char mtime[256];
4108         strftime(mtime, sizeof(mtime), "%F %T", tm);
4109         fprintf(fp,"mtime: %s\n", mtime);
4110 #if 0
4111 // people hit ctl-c waiting for this
4112         int fd = open(proc_path,O_RDONLY+O_NONBLOCK);
4113         if( fd < 0 ) { fprintf(fp,"open: %m\n"); return; }
4114         uint8_t *bfr = 0;
4115         int64_t bfrsz = 0;
4116         int64_t pagsz = sysconf(_SC_PAGE_SIZE);
4117         int64_t maxsz = 1024*pagsz;
4118         int64_t size = st.st_size, pos = 0;
4119         SHA1 sha1;
4120         while( (bfrsz = size-pos) > 0 ) {
4121                 if( bfrsz > maxsz ) bfrsz = maxsz;
4122                 bfr = (uint8_t *)mmap(NULL, bfrsz, PROT_READ,
4123                         MAP_PRIVATE+MAP_NORESERVE+MAP_POPULATE, fd, pos);
4124                 if( bfr == MAP_FAILED ) break;
4125                 sha1.addBytes(bfr, bfrsz);
4126                 munmap(bfr, bfrsz);
4127                 pos += bfrsz;
4128         }
4129         close(fd);
4130         ret = pos < size ? EIO : 0;
4131         fprintf(fp, "SHA1: ");
4132         uint8_t digest[20];  sha1.computeHash(digest);
4133         for( int i=0; i<20; ++i ) fprintf(fp, "%02x", digest[i]);
4134         if( ret < 0 ) fprintf(fp, " (ret %d)", ret);
4135         if( pos < st.st_size ) fprintf(fp, " (pos %jd)", pos);
4136 #endif
4137         fprintf(fp, "\n");
4138 }
4139
4140 void MWindow::trap_hook(FILE *fp, void *vp)
4141 {
4142         MWindow *mwindow = (MWindow *)vp;
4143 //      fprintf(fp, "\nPLUGINS:\n");
4144 //      mwindow->dump_plugins(fp);
4145         fprintf(fp, "\nEDL:\n");
4146         mwindow->dump_edl(fp);
4147         fprintf(fp, "\nUNDO:\n");
4148         mwindow->dump_undo(fp);
4149         fprintf(fp, "\nEXE: %s\n", AboutPrefs::build_timestamp);
4150         mwindow->dump_exe(fp);
4151 }
4152
4153
4154
4155
4156
4157
4158 int MWindow::save_defaults()
4159 {
4160         gui->save_defaults(defaults);
4161         edl->save_defaults(defaults);
4162         session->save_defaults(defaults);
4163         preferences->save_defaults(defaults);
4164
4165         for(int i = 0; i < plugin_guis->total; i++)
4166         {
4167 // Pointer comparison
4168                 plugin_guis->get(i)->save_defaults();
4169         }
4170         awindow->save_defaults(defaults);
4171
4172         defaults->save();
4173         return 0;
4174 }
4175
4176 int MWindow::run_script(FileXML *script)
4177 {
4178         int result = 0, result2 = 0;
4179         while(!result && !result2)
4180         {
4181                 result = script->read_tag();
4182                 if(!result)
4183                 {
4184                         if(script->tag.title_is("new_project"))
4185                         {
4186 // Run new in immediate mode.
4187 //                              gui->mainmenu->new_project->run_script(script);
4188                         }
4189                         else
4190                         if(script->tag.title_is("record"))
4191                         {
4192 // Run record as a thread.  It is a terminal command.
4193                                 ;
4194 // Will read the complete scipt file without letting record read it if not
4195 // terminated.
4196                                 result2 = 1;
4197                         }
4198                         else
4199                         {
4200                                 printf("MWindow::run_script: Unrecognized command: %s\n",script->tag.get_title() );
4201                         }
4202                 }
4203         }
4204         return result2;
4205 }
4206
4207 // ================================= synchronization
4208
4209
4210 int MWindow::interrupt_indexes()
4211 {
4212         mainprogress->cancelled = 1;
4213         mainindexes->interrupt_build();
4214         return 0;
4215 }
4216
4217
4218
4219 void MWindow::next_time_format()
4220 {
4221         switch(edl->session->time_format)
4222         {
4223                 case TIME_HMS: edl->session->time_format = TIME_HMSF; break;
4224                 case TIME_HMSF: edl->session->time_format = TIME_SAMPLES; break;
4225                 case TIME_SAMPLES: edl->session->time_format = TIME_SAMPLES_HEX; break;
4226                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_FRAMES; break;
4227                 case TIME_FRAMES: edl->session->time_format = TIME_FEET_FRAMES; break;
4228                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_SECONDS; break;
4229                 case TIME_SECONDS: edl->session->time_format = TIME_HMS; break;
4230         }
4231
4232         time_format_common();
4233 }
4234
4235 void MWindow::prev_time_format()
4236 {
4237         switch(edl->session->time_format)
4238         {
4239                 case TIME_HMS: edl->session->time_format = TIME_SECONDS; break;
4240                 case TIME_SECONDS: edl->session->time_format = TIME_FEET_FRAMES; break;
4241                 case TIME_FEET_FRAMES: edl->session->time_format = TIME_FRAMES; break;
4242                 case TIME_FRAMES: edl->session->time_format = TIME_SAMPLES_HEX; break;
4243                 case TIME_SAMPLES_HEX: edl->session->time_format = TIME_SAMPLES; break;
4244                 case TIME_SAMPLES: edl->session->time_format = TIME_HMSF; break;
4245                 case TIME_HMSF: edl->session->time_format = TIME_HMS; break;
4246         }
4247
4248         time_format_common();
4249 }
4250
4251 void MWindow::time_format_common()
4252 {
4253         gui->lock_window("MWindow::next_time_format");
4254         gui->redraw_time_dependancies();
4255
4256
4257         char string[BCTEXTLEN], string2[BCTEXTLEN];
4258         sprintf(string, _("Using %s"), Units::print_time_format(edl->session->time_format, string2));
4259         gui->show_message(string);
4260         gui->flush();
4261         gui->unlock_window();
4262 }
4263
4264
4265 int MWindow::set_filename(const char *filename)
4266 {
4267         if( filename != session->filename )
4268                 strcpy(session->filename, filename);
4269         if( filename != edl->path )
4270                 strcpy(edl->path, filename);
4271
4272         if(gui)
4273         {
4274                 if(filename[0] == 0)
4275                 {
4276                         gui->set_title(PROGRAM_NAME);
4277                 }
4278                 else
4279                 {
4280                         FileSystem dir;
4281                         char string[BCTEXTLEN], string2[BCTEXTLEN];
4282                         dir.extract_name(string, filename);
4283                         sprintf(string2, PROGRAM_NAME ": %s", string);
4284                         gui->set_title(string2);
4285                 }
4286         }
4287         return 0;
4288 }
4289
4290
4291
4292
4293
4294
4295
4296
4297 int MWindow::set_loop_boundaries()
4298 {
4299         double start = edl->local_session->get_selectionstart();
4300         double end = edl->local_session->get_selectionend();
4301
4302         if(start !=
4303                 end)
4304         {
4305                 ;
4306         }
4307         else
4308         if(edl->tracks->total_length())
4309         {
4310                 start = 0;
4311                 end = edl->tracks->total_length();
4312         }
4313         else
4314         {
4315                 start = end = 0;
4316         }
4317
4318         if(edl->local_session->loop_playback && start != end)
4319         {
4320                 edl->local_session->loop_start = start;
4321                 edl->local_session->loop_end = end;
4322         }
4323         return 0;
4324 }
4325
4326
4327
4328
4329
4330
4331
4332 int MWindow::reset_meters()
4333 {
4334         cwindow->gui->lock_window("MWindow::reset_meters 1");
4335         cwindow->gui->meters->reset_meters();
4336         cwindow->gui->unlock_window();
4337
4338         for(int j = 0; j < vwindows.size(); j++) {
4339                 VWindow *vwindow = vwindows[j];
4340                 if( !vwindow->is_running() ) continue;
4341                 vwindow->gui->lock_window("MWindow::reset_meters 2");
4342                 vwindow->gui->meters->reset_meters();
4343                 vwindow->gui->unlock_window();
4344         }
4345
4346         lwindow->gui->lock_window("MWindow::reset_meters 3");
4347         lwindow->gui->panel->reset_meters();
4348         lwindow->gui->unlock_window();
4349
4350         gui->lock_window("MWindow::reset_meters 4");
4351         gui->reset_meters();
4352         gui->unlock_window();
4353         return 0;
4354 }
4355
4356
4357 void MWindow::resync_guis()
4358 {
4359 // Update GUIs
4360         restart_brender();
4361         gui->lock_window("MWindow::resync_guis");
4362         gui->update(1, 1, 1, 1, 1, 1, 0);
4363         gui->unlock_window();
4364
4365         cwindow->gui->lock_window("MWindow::resync_guis");
4366         cwindow->gui->resize_event(cwindow->gui->get_w(),
4367                 cwindow->gui->get_h());
4368         int channels = edl->session->audio_channels;
4369         cwindow->gui->meters->set_meters(channels, 1);
4370         cwindow->gui->flush();
4371         cwindow->gui->unlock_window();
4372
4373         for(int i = 0; i < vwindows.size(); i++) {
4374                 VWindow *vwindow = vwindows[i];
4375                 if( !vwindow->is_running() ) continue;
4376                 vwindow->gui->lock_window("MWindow::resync_guis");
4377                 vwindow->gui->resize_event(vwindow->gui->get_w(),
4378                         vwindow->gui->get_h());
4379                 vwindow->gui->meters->set_meters(channels, 1);
4380                 vwindow->gui->flush();
4381                 vwindow->gui->unlock_window();
4382         }
4383
4384         lwindow->gui->lock_window("MWindow::resync_guis");
4385         lwindow->gui->panel->set_meters(channels, 1);
4386         lwindow->gui->flush();
4387         lwindow->gui->unlock_window();
4388
4389 // Warn user
4390         if(((edl->session->output_w % 4) ||
4391                 (edl->session->output_h % 4)) &&
4392                 edl->session->playback_config->vconfig->driver == PLAYBACK_X11_GL)
4393         {
4394                 MainError::show_error(
4395                         _("This project's dimensions are not multiples of 4 so\n"
4396                         "it can't be rendered by OpenGL."));
4397         }
4398
4399
4400 // Flash frame
4401         sync_parameters(CHANGE_ALL);
4402 }
4403
4404 int MWindow::select_asset(Asset *asset, int vstream, int astream, int delete_tracks)
4405 {
4406         File *file = new File;
4407         EDLSession *session = edl->session;
4408         double old_framerate = session->frame_rate;
4409         double old_samplerate = session->sample_rate;
4410         int old_auto_keyframes = session->auto_keyframes;
4411         session->auto_keyframes = 0;
4412         int result = file->open_file(preferences, asset, 1, 0);
4413         if( !result && delete_tracks > 0 )
4414                 undo->update_undo_before();
4415         int video_layers = asset->get_video_layers();
4416         if( !result && asset->video_data && vstream < video_layers ) {
4417                 // try to get asset up to date, may fail
4418                 file->select_video_stream(asset, vstream);
4419                 // either way use what was/is there.
4420                 double framerate = asset->get_frame_rate();
4421                 int width = asset->get_w();
4422                 int height = asset->get_h();
4423                 // must be multiple of 4 for opengl
4424                 width = (width+3) & ~3;  height = (height+3) & ~3;
4425                 int driver = session->playback_config->vconfig->driver;
4426                 int color_model = file->get_best_colormodel(asset, driver);
4427 //              color_model = BC_CModels::is_yuv(color_model) ?
4428 //                              BC_CModels::has_alpha(color_model) ? BC_YUVA8888 : BC_YUV888 :
4429 //                      BC_CModels::is_float(color_model) ?
4430 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA_FLOAT : BC_RGB_FLOAT :
4431 //                              BC_CModels::has_alpha(color_model) ? BC_RGBA8888 : BC_RGB888;
4432 // have alpha for now
4433                 color_model = BC_CModels::is_yuv(color_model) ?  BC_YUVA8888 :
4434                         BC_CModels::is_float(color_model) ? BC_RGBA_FLOAT : BC_RGBA8888;
4435                 session->color_model = color_model;
4436                 session->output_w = width;
4437                 session->output_h = height;
4438                 session->frame_rate = framerate;
4439                 // not, asset->actual_width/actual_height
4440                 asset->width = session->output_w;
4441                 asset->height = session->output_h;
4442                 asset->frame_rate = session->frame_rate;
4443                 create_aspect_ratio(session->aspect_w, session->aspect_h,
4444                         session->output_w, session->output_h);
4445                 Track *track = edl->tracks->first;
4446                 for( Track *next_track=0; track; track=next_track ) {
4447                         next_track = track->next;
4448                         if( track->data_type != TRACK_VIDEO ) continue;
4449                         if( delete_tracks ) {
4450                                 Edit *edit = track->edits->first;
4451                                 for( Edit *next_edit=0; edit; edit=next_edit ) {
4452                                         next_edit = edit->next;
4453                                         if( edit->channel != vstream ||
4454                                             !edit->asset || !edit->asset->is_asset ||
4455                                             !asset->equivalent(*edit->asset,1,1,edl) )
4456                                                 delete edit;
4457                                 }
4458                         }
4459                         if( track->edits->first ) {
4460                                 track->track_w = edl->session->output_w;
4461                                 track->track_h = edl->session->output_h;
4462                         }
4463                         else if( delete_tracks )
4464                                 edl->tracks->delete_track(track);
4465                 }
4466                 edl->retrack();
4467                 edl->resample(old_framerate, session->frame_rate, TRACK_VIDEO);
4468         }
4469         if( !result && asset->audio_data && asset->channels > 0 ) {
4470                 session->sample_rate = asset->get_sample_rate();
4471                 int64_t channel_mask = 0;
4472                 int astrm = !asset->video_data || vstream >= video_layers ? -1 :
4473                         file->get_audio_for_video(vstream, astream, channel_mask);
4474                 if( astrm >= 0 ) file->select_audio_stream(asset, astrm);
4475                 if( astrm < 0 || !channel_mask ) channel_mask = (1<<asset->channels)-1;
4476                 int channels = 0;
4477                 for( uint64_t mask=channel_mask; mask!=0; mask>>=1 ) channels += mask & 1;
4478                 if( channels < 1 ) channels = 1;
4479                 if( channels > 6 ) channels = 6;
4480                 session->audio_tracks = session->audio_channels = channels;
4481
4482                 int *achannel_positions = preferences->channel_positions[session->audio_channels-1];
4483                 memcpy(&session->achannel_positions, achannel_positions, sizeof(session->achannel_positions));
4484                 remap_audio(MWindow::AUDIO_1_TO_1);
4485
4486                 if( delete_tracks ) {
4487                         Track *track = edl->tracks->first;
4488                         for( Track *next_track=0; track; track=next_track ) {
4489                                 next_track = track->next;
4490                                 if( track->data_type != TRACK_AUDIO ) continue;
4491                                 Edit *edit = track->edits->first;
4492                                         for( Edit *next_edit=0; edit; edit=next_edit ) {
4493                                         next_edit = edit->next;
4494                                         if( !((1<<edit->channel) & channel_mask) ||
4495                                             !edit->asset || !edit->asset->is_asset ||
4496                                             !asset->equivalent(*edit->asset,1,1,edl) )
4497                                                 delete edit;
4498                                 }
4499                                 if( !track->edits->first )
4500                                         edl->tracks->delete_track(track);
4501                         }
4502                 }
4503                 edl->rechannel();
4504                 edl->resample(old_samplerate, session->sample_rate, TRACK_AUDIO);
4505         }
4506         delete file;
4507         session->auto_keyframes = old_auto_keyframes;
4508         if( !result && delete_tracks > 0 ) {
4509                 save_backup();
4510                 undo->update_undo_after(_("select asset"), LOAD_ALL);
4511         }
4512         resync_guis();
4513         return result;
4514 }
4515
4516 int MWindow::select_asset(int vtrack, int delete_tracks)
4517 {
4518         Track *track = edl->tracks->get(vtrack, TRACK_VIDEO);
4519         if( !track )
4520                 track = edl->tracks->get(vtrack, TRACK_AUDIO);
4521         if( !track ) return 1;
4522         Edit *edit = track->edits->first;
4523         if( !edit ) return 1;
4524         Asset *asset = edit->asset;
4525         if( !asset || !asset->is_asset ) return 1;
4526         return select_asset(asset, edit->channel, 0, delete_tracks);
4527 }
4528
4529 void MWindow::dump_plugindb(FILE *fp)
4530 {
4531         if( !plugindb ) return;
4532         for(int i = 0; i < plugindb->total; i++)
4533                 plugindb->get(i)->dump(fp);
4534 }
4535
4536 FloatAuto* MWindow::get_float_auto(PatchGUI *patch,int idx)
4537 {
4538         Auto *current = 0;
4539         double unit_position = edl->local_session->get_selectionstart(1);
4540         unit_position = patch->track->to_units(unit_position, 0);
4541
4542         FloatAutos *ptr = (FloatAutos*)patch->track->automation->autos[idx];
4543         return (FloatAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4544 }
4545
4546 IntAuto* MWindow::get_int_auto(PatchGUI *patch,int idx)
4547 {
4548         Auto *current = 0;
4549         double unit_position = edl->local_session->get_selectionstart(1);
4550         unit_position = patch->track->to_units(unit_position, 0);
4551
4552         IntAutos *ptr = (IntAutos*)patch->track->automation->autos[idx];
4553         return (IntAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4554 }
4555
4556 PanAuto* MWindow::get_pan_auto(PatchGUI *patch)
4557 {
4558         Auto *current = 0;
4559         double unit_position = edl->local_session->get_selectionstart(1);
4560         unit_position = patch->track->to_units(unit_position, 0);
4561
4562         PanAutos *ptr = (PanAutos*)patch->track->automation->autos[AUTOMATION_PAN];
4563         return (PanAuto*)ptr->get_prev_auto( (long)unit_position, PLAY_FORWARD, current);
4564 }
4565
4566 PatchGUI *MWindow::get_patchgui(Track *track)
4567 {
4568         PatchGUI *patchgui = 0;
4569         TimelinePane **panes = gui->pane;
4570         for( int i=0; i<TOTAL_PANES && !patchgui; ++i ) {
4571                 if( !panes[i] ) continue;
4572                 PatchBay *patchbay = panes[i]->patchbay;
4573                 if( !patchbay ) continue;
4574                 for( int j=0; j<patchbay->patches.total && !patchgui; ++j ) {
4575                         if( patchbay->patches.values[j]->track == track )
4576                                 patchgui = patchbay->patches.values[j];
4577                 }
4578         }
4579         return patchgui;
4580 }
4581