added scons option BF_WITH_PYTHON (defined as DISABLE_PYTHON)
[blender-staging.git] / source / blender / src / editscreen.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV.
21  * All rights reserved.
22  *
23  * The Original Code is: all of this file.
24  *
25  * Contributor(s): none yet.
26  *
27  * ***** END GPL LICENSE BLOCK *****
28  * All screen functions that are related to the interface
29  * handling and drawing. Might be split up as well later...
30  */
31
32 #ifdef HAVE_CONFIG_H
33 #include <config.h>
34 #endif
35
36 #include "nla.h"
37
38 #include <stdlib.h>
39 #include <string.h>
40 #include <ctype.h>  /* isprint */
41 #include <stdio.h>
42 #include <math.h>
43
44 #include "GHOST_Types.h"
45
46 #include "MEM_guardedalloc.h"
47
48 #include "PIL_time.h"
49
50 #include "BMF_Api.h"
51
52 #include "BLI_blenlib.h"
53 #include "BLI_arithb.h"
54
55 #include "IMB_imbuf_types.h"
56 #include "IMB_imbuf.h"
57
58 #include "DNA_action_types.h"
59 #include "DNA_object_types.h"
60 #include "DNA_scene_types.h"
61 #include "DNA_screen_types.h"
62 #include "DNA_space_types.h"
63 #include "DNA_sound_types.h"
64 #include "DNA_view3d_types.h"
65 #include "DNA_userdef_types.h"
66
67 #include "BLO_writefile.h"
68
69 #include "BKE_utildefines.h"
70 #include "BKE_global.h"
71 #include "BKE_library.h"
72 #include "BKE_main.h"
73 #include "BKE_blender.h"
74 #include "BKE_screen.h"
75
76 #ifdef WITH_VERSE
77 #include "BKE_verse.h"
78 #endif
79
80 #include "BIF_cursors.h"
81 #include "BIF_drawscene.h"
82 #include "BIF_editsound.h"
83 #include "BIF_glutil.h"
84 #include "BIF_gl.h"
85 #include "BIF_graphics.h"
86 #include "BIF_interface.h"
87 #include "BIF_interface_icons.h"
88 #include "BIF_mainqueue.h"
89 #include "BIF_mywindow.h"
90 #include "BIF_previewrender.h"
91 #include "BIF_renderwin.h"
92 #include "BIF_retopo.h"
93 #include "BIF_screen.h"
94 #include "BIF_space.h"
95 #include "BIF_toets.h"
96 #include "BIF_toolbox.h"
97 #include "BIF_usiblender.h"
98 #include "BIF_keyval.h"
99 #include "BIF_resources.h"
100
101 #include "BSE_edit.h"
102 #include "BSE_filesel.h"
103 #include "BSE_headerbuttons.h"
104 #include "BSE_seqaudio.h"
105 #include "BSE_view.h"
106
107 #ifndef DISABLE_PYTHON
108 #include "BPY_extern.h"
109 #endif
110
111 #include "mydevice.h"
112 #include "blendef.h"
113
114 #include "winlay.h"
115
116 /* TIPS:
117  * 
118  * - WATCH THE EDGES,  VERTICES HAVE TO BE IN ORDER...
119          (lowest pointer first). Otherwise unpredictable effects!
120  * - problem: flags here are not nicely implemented. After usage
121          always reset to zero.
122  */
123
124 /* comment added to test orange branch */
125
126 static void testareas(void);
127 static void area_autoplayscreen(void);
128 static void wait_for_event(void);
129
130
131 /* ********* Globals *********** */
132
133 static Window *mainwin= NULL;
134 static int prefsizx= 0, prefsizy= 0, prefstax= 0, prefstay= 0, start_maximized= 1;
135 static short dodrawscreen= 1;
136 static ScrArea *areawinar[MAXWIN];
137 static ScrArea *g_activearea= NULL;
138 short winqueue_break= 0;
139 ScrArea *curarea= 0;
140
141 /* prototypes -------------------*/
142 int afterqtest(short win, unsigned short evt);
143 unsigned short screen_qread(short *val, char *ascii);
144 void add_to_mainqueue(Window *win, void *user_data, short evt, short val, char ascii);
145 static void drawscredge_area(ScrArea *sa);
146
147 /**********************************************************************/
148
149 extern int textediting;
150
151 static void screen_set_cursor(bScreen *sc) 
152 {
153         if (sc->winakt>3) {
154                 ScrArea *sa= areawinar[sc->winakt];
155
156                 set_cursor(sa->cursor);
157         } else {
158                 set_cursor(CURSOR_STD);
159         }
160 }
161
162 void waitcursor(int val)
163 {
164         if(G.curscreen) {
165                 if(val) {
166                         set_cursor(CURSOR_WAIT);
167                 } else {
168                         screen_set_cursor(G.curscreen);
169                 }
170         }
171 }
172
173 static int choose_cursor(ScrArea *sa)
174 {
175         if (sa->spacetype==SPACE_VIEW3D) {
176                 if(G.obedit) return CURSOR_EDIT;
177                 else if(G.f & (G_VERTEXPAINT|G_WEIGHTPAINT|G_TEXTUREPAINT))
178                                 return CURSOR_VPAINT;
179                 else if(FACESEL_PAINT_TEST) return CURSOR_FACESEL;
180                 else if(G.f & G_SCULPTMODE) return CURSOR_EDIT;
181                 else if(G.f & G_PARTICLEEDIT) return CURSOR_EDIT;
182                 else return CURSOR_STD;
183         }
184         else if (sa->spacetype==SPACE_TEXT) {
185                 return CURSOR_TEXTEDIT;
186         }
187         else {
188                 return CURSOR_STD;
189         }
190 }
191
192 void wich_cursor(ScrArea *sa)
193 {
194         sa->cursor= choose_cursor(sa);
195         
196         /* well... the waitcursor() is not a state, so this call will cancel it out */
197         if(get_cursor()!=CURSOR_WAIT)
198                 screen_set_cursor(G.curscreen);
199 }
200
201
202 void setcursor_space(int spacetype, short cur)
203 {
204         bScreen *sc;
205         ScrArea *sa;
206
207         for (sc= G.main->screen.first; sc; sc= sc->id.next)
208                 for (sa= sc->areabase.first; sa; sa= sa->next)
209                         if(sa->spacetype==spacetype)
210                                 sa->cursor= cur;
211
212         screen_set_cursor(G.curscreen);
213 }
214
215
216 /* *********  IN/OUT  ************* */
217
218 void getmouseco_sc(short *mval)         /* screen coordinates */
219 {
220         getmouse(mval);
221 }
222
223 /* mouse_cursor called during a script (via Window.QHandle) need
224  * this function for getmouseco_areawin to work: */
225 void set_g_activearea(ScrArea *sa)
226 {
227         if (sa) g_activearea = sa;
228 }
229
230 void getmouseco_areawin(short *mval)            /* internal area coordinates */
231 {
232         getmouseco_sc(mval);
233         
234         if(g_activearea && g_activearea->win) {
235                 mval[0]-= g_activearea->winrct.xmin;
236                 mval[1]-= g_activearea->winrct.ymin;
237         }
238 }
239
240 void getmouseco_headwin(short *mval)            /* internal area coordinates */
241 {
242         getmouseco_sc(mval);
243         
244         if(g_activearea && g_activearea->headwin) {
245                 mval[0]-= g_activearea->headrct.xmin;
246                 mval[1]-= g_activearea->headrct.ymin;
247         }
248 }
249
250 void headerprint(char *str)
251 {
252         if(curarea->headertype) {
253                 areawinset(curarea->headwin);
254                 
255                 headerbox(curarea);
256                 
257                 BIF_ThemeColor(TH_MENU_TEXT); /* better than cpack(0x0) color no? (desoto) */
258                 glRasterPos2i(20+curarea->headbutofs,  6);
259                 BMF_DrawString(G.font, str);
260                 
261                 curarea->head_swap= WIN_BACK_OK;
262                 areawinset(curarea->win);
263         }
264         else {
265                 // dunno... thats for later (ton)
266         }
267 }
268
269 /* *********** STUFF ************** */
270
271 static int scredge_is_horizontal(ScrEdge *se)
272 {
273         return (se->v1->vec.y == se->v2->vec.y);
274 }
275
276 static ScrEdge *screen_find_active_scredge(bScreen *sc, short *mval)
277 {
278         ScrEdge *se;
279         
280         for (se= sc->edgebase.first; se; se= se->next) {
281                 if (scredge_is_horizontal(se)) {
282                         short min, max;
283                         min= MIN2(se->v1->vec.x, se->v2->vec.x);
284                         max= MAX2(se->v1->vec.x, se->v2->vec.x);
285                         
286                         if (abs(mval[1]-se->v1->vec.y)<=2 && mval[0] >= min && mval[0]<=max)
287                                 return se;
288                 } 
289                 else {
290                         short min, max;
291                         min= MIN2(se->v1->vec.y, se->v2->vec.y);
292                         max= MAX2(se->v1->vec.y, se->v2->vec.y);
293
294                         if (abs(mval[0]-se->v1->vec.x)<=2 && mval[1] >= min && mval[1]<=max)
295                                 return se;
296                 }
297         }
298         
299         return NULL;
300 }
301
302 void areawinset(short win)
303 {
304         if(win>3) {
305                 curarea= areawinar[win];
306                 if(curarea==0) {
307                         printf("error in areawinar %d ,areawinset\n", win);
308                         return;
309                 }
310                 
311                 BIF_SetTheme(curarea);
312                 
313                 switch(curarea->spacetype) {
314                 case SPACE_VIEW3D:
315                         G.vd= curarea->spacedata.first;
316                         break;
317                 case SPACE_IPO:
318                         G.sipo= curarea->spacedata.first;
319                         G.v2d= &G.sipo->v2d;
320                         break;
321                 case SPACE_BUTS:
322                         G.buts= curarea->spacedata.first;
323                         G.v2d= &G.buts->v2d;
324                         break;
325                 case SPACE_SEQ: {
326                         SpaceSeq *sseq= curarea->spacedata.first;
327                         G.v2d= &sseq->v2d;
328                         break;
329                 }
330                 case SPACE_OOPS:
331                         G.soops= curarea->spacedata.first;
332                         G.v2d= &G.soops->v2d;
333                         break;
334                 case SPACE_IMAGE:
335                         G.sima= curarea->spacedata.first;
336                         G.v2d= &G.sima->v2d;
337                         break;
338                 case SPACE_SOUND:
339                         G.ssound= curarea->spacedata.first;
340                         G.v2d= &G.ssound->v2d;
341                         break;
342                 case SPACE_ACTION:
343                         G.saction= curarea->spacedata.first;
344                         G.v2d= &G.saction->v2d;
345                         break;
346                 case SPACE_NLA:
347                         G.snla= curarea->spacedata.first;
348                         G.v2d= &G.snla->v2d;
349                         break;
350                 case SPACE_TIME:
351                 {
352                         SpaceTime *stime= curarea->spacedata.first;
353                         G.v2d= &stime->v2d;
354                 }
355                         break;
356                 case SPACE_NODE:
357                 {
358                         SpaceNode *snode= curarea->spacedata.first;
359                         G.v2d= &snode->v2d;
360                 }
361                         break;
362                 case SPACE_IMASEL:
363                 {
364                         SpaceImaSel *simasel= curarea->spacedata.first;
365                         G.v2d= &simasel->v2d;
366                 }
367                 default:
368                         break;
369                 }
370         }
371         
372         if(win) mywinset(win);
373 }
374
375 #define SCR_BACK 0.55
376 #define SCR_ROUND 12
377
378 void headerbox(ScrArea *area)
379 {
380         float width= area->winx;
381         int active=0;
382
383         glClearColor(SCR_BACK, SCR_BACK, SCR_BACK, 0.0);
384         glClear(GL_COLOR_BUFFER_BIT);
385
386         active= area_is_active_area(area);
387
388         if(active) BIF_ThemeColor(TH_HEADER);
389         else BIF_ThemeColor(TH_HEADERDESEL);
390
391         /* weird values here... is because of window matrix that centers buttons */
392         if(area->headertype==HEADERTOP) {
393                 uiSetRoundBox(3);
394                 uiRoundBoxEmboss(-0.5+area->headbutofs, -10.0, width-1.5+area->headbutofs, HEADERY-2.0, SCR_ROUND, active);
395         }
396         else {
397                 uiSetRoundBox(12);
398                 uiRoundBoxEmboss(-0.5+area->headbutofs, -3.5, width-1.5+area->headbutofs, HEADERY+10, SCR_ROUND, active);
399         }
400         
401         uiSetRoundBox(15);
402 }
403
404 int area_is_active_area(ScrArea *area)
405 {
406         return (g_activearea && area==g_activearea);
407 }
408
409 void scrarea_do_headdraw(ScrArea *area)
410 {
411         if (area->headertype) {
412                 areawinset(area->headwin);
413         
414                 headerbox(area);
415                 
416                 /* we make scissor test slightly smaller not to destroy rounded headers */
417                 glScissor(area->headrct.xmin+5, area->headrct.ymin, area->winx-10, HEADERY);
418                 
419                 switch(area->spacetype) {
420                 case SPACE_FILE:        file_buttons();         break;
421                 case SPACE_INFO:        info_buttons();         break;
422                 case SPACE_VIEW3D:      view3d_buttons();       break;
423                 case SPACE_IPO:         ipo_buttons();          break;
424                 case SPACE_BUTS:        buts_buttons();         break;
425                 case SPACE_SEQ:         seq_buttons();          break;
426                 case SPACE_IMAGE:       image_buttons();        break;
427                 case SPACE_IMASEL:      imasel_buttons();       break;
428                 case SPACE_OOPS:        oops_buttons();         break;
429                 case SPACE_TEXT:        text_buttons();         break;
430                 case SPACE_SCRIPT:script_buttons();             break;
431                 case SPACE_SOUND:       sound_buttons();        break;
432                 case SPACE_ACTION:      action_buttons();       break;
433                 case SPACE_NLA:         nla_buttons();          break;
434                 case SPACE_TIME:        time_buttons(area);     break;
435                 case SPACE_NODE:        node_buttons(area);     break;
436                 }
437                 uiClearButLock();
438
439                 //glScissor(area->winrct.xmin, area->winrct.xmax, area->winx, area->winy);
440                 area->head_swap= WIN_BACK_OK;
441         }
442 }
443 void scrarea_do_headchange(ScrArea *area)
444 {
445         float ofs= area->headbutofs;
446
447         if (area->headertype==HEADERDOWN) {
448                 bwin_ortho2(area->headwin, -0.375+ofs, area->headrct.xmax-area->headrct.xmin-0.375+ofs, -3.375, area->headrct.ymax-area->headrct.ymin-3.375+1.0);
449         } else if (area->headertype==HEADERTOP) {
450                 bwin_ortho2(area->headwin, -0.375+ofs, area->headrct.xmax-area->headrct.xmin-0.375+ofs, -2.375-1.0, area->headrct.ymax-area->headrct.ymin-2.375);
451         }
452 }
453
454
455 static void openheadwin(ScrArea *sa);
456 static void closeheadwin(ScrArea *sa);
457
458 static void scrarea_change_headertype(ScrArea *sa, int newtype) 
459 {
460         sa->headertype= newtype;
461
462         if (!newtype) {
463                 if (sa->headwin) {
464                         uiFreeBlocksWin(&sa->uiblocks, sa->headwin);
465                         closeheadwin(sa);
466                 }
467         } else {
468                 if (!sa->headwin) {
469                         openheadwin(sa);
470                 }
471         }
472
473         testareas();
474         mainqenter(DRAWEDGES, 1);
475         winqueue_break= 1;
476 }
477
478 static void headmenu(ScrArea *sa)
479 {
480         short val= pupmenu("Header %t|Top%x2|Bottom %x1|No Header %x0");
481         
482         if(val> -1) {
483                 scrarea_change_headertype(sa, val);
484         }
485 }
486
487 static void addqueue_ext(short win, unsigned short event, short val, char ascii)
488 {
489         if (win<4 || !areawinar[win]) {
490                 /* other win ids are for mainwin & renderwin */
491         } 
492         else {
493                 BWinEvent evt;
494
495                 memset(&evt, 0, sizeof(evt));
496                 evt.event= event;
497                 evt.val= val;
498                 evt.ascii= ascii;
499                 
500                 bwin_qadd(win, &evt);
501         }
502 }
503
504 void addqueue(short win, unsigned short event, short val)
505 {
506         addqueue_ext(win, event, val, 0);
507 }
508
509 void scrarea_queue_winredraw(ScrArea *area)
510 {
511         addqueue(area->win, REDRAW, 1);
512 }
513 void scrarea_queue_headredraw(ScrArea *area)
514 {
515         if (area->headwin) addqueue(area->headwin, REDRAW, 1);
516 }
517 void scrarea_queue_redraw(ScrArea *area)
518 {
519         scrarea_queue_winredraw(area);
520         scrarea_queue_headredraw(area);
521 }
522
523 static void scrollheader(ScrArea *area);
524 static void scrarea_dispatch_header_events(ScrArea *sa)
525 {
526         ScrArea *tempsa;
527         BWinEvent evt;
528         short do_redraw=0, do_change=0;
529         
530         areawinset(sa->headwin);
531         
532         while(bwin_qread(sa->headwin, &evt)) {
533                 if(evt.val) {
534                         if( uiDoBlocks(&curarea->uiblocks, evt.event, 1)!=UI_NOTHING ) evt.event= 0;
535
536                         switch(evt.event) {
537                         case UI_BUT_EVENT:
538                                 do_headerbuttons(evt.val);
539                                 break;
540                         
541                         case LEFTMOUSE:
542                                 if (G.qual & LR_CTRLKEY) {
543                                         window_lower(mainwin);
544                                 } else {
545                                         window_raise(mainwin);
546                                 }
547                                 break;
548
549                         case MIDDLEMOUSE:
550                                 scrollheader(sa);
551                                 break;
552                         case RIGHTMOUSE:
553                                 headmenu(sa);
554                                 break;
555                         case REDRAW:
556                                 do_redraw= 1;
557                                 break;
558                         case CHANGED:
559                                 sa->head_swap= 0;
560                                 do_change= 1;
561                                 do_redraw= 1;
562                                 break;
563                         default:
564                                 if (winqueue_break == 0) {
565                                         scrarea_do_winhandle(sa, &evt);
566                                         if (winqueue_break == 0) areawinset(sa->headwin);
567                                 }
568                         }
569                         
570                         if(winqueue_break) return;
571                 }
572         }
573
574         /* test: does window still exist? */    
575         tempsa= areawinar[sa->headwin];
576         if(tempsa==0) return;
577         
578         /* this functional separation does not work as well as i expected... */
579         if(do_change) scrarea_do_headchange(sa);
580         if(do_redraw) scrarea_do_headdraw(sa);
581 }
582
583 static void scrarea_dispatch_events(ScrArea *sa)
584 {
585         ScrArea *tempsa;
586         BWinEvent evt;
587         short do_redraw=0, do_change=0;
588         
589         if(sa!=curarea || sa->win!=mywinget()) areawinset(sa->win);
590
591         while(bwin_qread(sa->win, &evt)) {
592                 if(evt.event==REDRAW) {
593                         do_redraw= 1;
594                 }
595                 else if(evt.event==CHANGED) {
596                         sa->win_swap= 0;
597                         do_change= 1;
598                         do_redraw= 1;
599                 }
600                 else {
601                         scrarea_do_winhandle(sa, &evt);
602                 }
603                 
604                 if(winqueue_break) return;
605         }
606
607         /* test: does window still exist */     
608         tempsa= areawinar[sa->win];
609         if(tempsa==0) return;
610
611         if (do_change || do_redraw) {
612                 areawinset(sa->win);
613                 if(do_change)
614                         scrarea_do_winchange(curarea);
615                 if(do_redraw)
616                         scrarea_do_windraw(curarea);
617         }
618 }
619
620 /***/
621
622
623 void markdirty_all()
624 {
625         ScrArea *sa;
626         for (sa= G.curscreen->areabase.first; sa; sa= sa->next) {
627                 if(sa->win) {
628                         scrarea_queue_winredraw(sa);
629                         sa->win_swap &= ~WIN_FRONT_OK;
630                 }
631                 if(sa->headwin) {
632                         scrarea_queue_headredraw(sa);
633                         sa->head_swap &= ~WIN_FRONT_OK;
634                 }
635         }
636 }
637
638 /* but no redraw! */
639 void markdirty_all_back(void)
640 {
641         ScrArea *sa;
642         
643         for (sa= G.curscreen->areabase.first; sa; sa= sa->next) {
644                 if(sa->win) {
645                         sa->win_swap &= ~WIN_BACK_OK;
646                 }
647                 if(sa->headwin) {
648                         sa->head_swap &= ~WIN_BACK_OK;
649                 }
650         }
651         
652         /* if needed; backbuffer selection redraw */
653         if(G.vd) G.vd->flag |= V3D_NEEDBACKBUFDRAW;
654
655 }
656
657 void markdirty_win_back(short winid)
658 {
659         ScrArea *sa= areawinar[winid];
660         if(sa) {
661                 if(sa->win==winid) sa->win_swap &= ~WIN_BACK_OK;
662                 else sa->head_swap &= ~WIN_BACK_OK;
663         }
664 }
665
666
667 int is_allowed_to_change_screen(bScreen *new)
668 {
669         /* not when curscreen is full
670          * not when obedit && old->scene!=new->scene
671          */
672         
673         if(new==0) return 0;
674         if(G.curscreen->full != SCREENNORMAL) return 0;
675         if(curarea->full) return 0;
676         if(G.obedit) {
677                 if(G.curscreen->scene!=new->scene) return 0;
678         }
679         return 1;
680 }
681
682 void splash(void *data, int datasize, char *string)
683 {
684         ImBuf *bbuf;
685         int oldwin;
686         short val;
687
688         bbuf= IMB_ibImageFromMemory((int *)data, datasize, IB_rect);
689
690         if (bbuf) {
691                 oldwin = mywinget();
692                 mywinset(G.curscreen->mainwin);
693                 
694                 if (string) {
695                         int x, y, maxy;
696                         unsigned int *rect;
697                         
698                         rect = bbuf->rect;
699                         maxy = MIN2(bbuf->y, 18);
700
701                         for (y = 0; y < maxy; y++) {
702                                 for (x = 0; x < bbuf->x; x++) {
703                                         *rect = 0xffffffff;
704                                         rect++;
705                                 }
706                         }
707                 }
708                 glDrawBuffer(GL_FRONT);
709                 
710                 uiDrawBoxShadow(200, (prefsizx-bbuf->x)/2, (prefsizy-bbuf->y)/2, (prefsizx+bbuf->x)/2, (prefsizy+bbuf->y)/2);
711                 
712                 glRasterPos2i((prefsizx-bbuf->x)/2, (prefsizy-bbuf->y)/2);      
713                 glDrawPixels(bbuf->x, bbuf->y, GL_RGBA, GL_UNSIGNED_BYTE, bbuf->rect);
714
715                 if (string) {
716                         void *font;
717                         int width;                      
718                         
719                         if (BMF_GetStringWidth(font= G.font, string) > bbuf->x)
720                                 if (BMF_GetStringWidth(font= G.fonts, string) > bbuf->x)
721                                         font= G.fontss;
722                         
723                         width= BMF_GetStringWidth(font, string);
724                                                 
725                         glColor3ub(0, 0, 0);
726                         glRasterPos2i((prefsizx-width)/2, (prefsizy-bbuf->y)/2 + 6);
727                         BMF_DrawString(font, string);
728                 }
729
730                 bglFlush();
731                 glDrawBuffer(GL_BACK);
732                 
733                 IMB_freeImBuf(bbuf);
734                 
735                 // flush input buffers ....
736                 // this might break some things
737
738                 while (get_mbut()) {
739                         BIF_wait_for_statechange();
740                 }
741                 while(qtest()) {
742                         extern_qread(&val);
743                 }
744
745                 wait_for_event();
746                 
747                 mywinset(oldwin);
748                 markdirty_all();
749                 mainqenter(DRAWEDGES, 1);
750         }
751 }
752
753 static void moveareas(ScrEdge *edge);
754 static void joinarea_interactive(ScrArea *area, ScrEdge *onedge);
755 static void splitarea_interactive(ScrArea *area, ScrEdge *onedge);
756 static ScrArea *test_edge_area(ScrArea *sa, ScrEdge *se);
757 static ScrEdge *screen_findedge(bScreen *sc, ScrVert *v1, ScrVert *v2);
758
759 static int isjoinable(ScrArea *area, ScrEdge *onedge)
760 {
761         struct ScrArea *sa1 = area, *sa2;
762         struct ScrEdge *se;
763         
764         sa1 = test_edge_area(sa1, onedge);
765         if(sa1==0) return 0;
766
767         /* find directions with same edge */
768         sa2= G.curscreen->areabase.first;
769         while(sa2) {
770                 if(sa2 != sa1) {
771                         se= screen_findedge(G.curscreen, sa2->v1, sa2->v2);
772                         if(onedge==se) return 1;
773                         se= screen_findedge(G.curscreen, sa2->v2, sa2->v3);
774                         if(onedge==se) return 1;
775                         se= screen_findedge(G.curscreen, sa2->v3, sa2->v4);
776                         if(onedge==se) return 1;
777                         se= screen_findedge(G.curscreen, sa2->v4, sa2->v1);
778                         if(onedge==se) return 1;
779                 }
780                 sa2= sa2->next;
781         }
782         
783         return 0;               
784 }
785
786 static void screen_edge_edit_event(ScrArea *actarea, ScrEdge *actedge, short evt, short val) 
787 {
788         if (val) {
789                         // don't allow users to edit full screens
790                 if (actarea && actarea->full)
791                         return;
792         
793                 if (evt==LEFTMOUSE) {
794                         moveareas(actedge);
795                 } else if (evt==MIDDLEMOUSE || evt==RIGHTMOUSE) {
796                         int edgeop;
797                         char str[64] = "Split Area%x1|";
798                         
799                         if(isjoinable(actarea, actedge))        strcat(str, "Join Areas%x2|");
800                         if (actarea->headertype)                        strcat(str, "No Header%x3");
801                         else                                                            strcat(str, "Add Header%x3");
802                         
803                         edgeop= pupmenu(str);
804                         if      (edgeop==1)     splitarea_interactive(actarea, actedge);
805                         else if (edgeop==2)     joinarea_interactive(actarea, actedge);
806                         else if (edgeop==3)     scrarea_change_headertype(actarea,
807                                                                                 actarea->headertype?0:HEADERDOWN);
808                 }
809                 else blenderqread(evt, val);    // global hotkeys
810         }
811 }
812
813 /***/
814
815 extern void mywindow_init_mainwin(Window *win, int orx, int ory, int sizex, int sizey);
816 void test_scale_screen(bScreen *);
817
818 static void resize_screens(int x, int y, int w, int h) {
819         prefstax= x;
820         prefstay= y;
821         prefsizx= w;
822         prefsizy= h;
823
824         test_scale_screen(G.curscreen);
825         testareas();
826 }
827
828 static void init_mainwin(void)
829 {
830         int orx, ory, sizex, sizey;
831         
832         glEnable(GL_SCISSOR_TEST);
833
834         window_get_position(mainwin, &orx, &ory);
835         window_get_size(mainwin, &sizex, &sizey);
836
837                 /* XXX, temporary stupid fix for minimize at windows */
838         if (!sizex && !sizey) {
839                 return;
840         }
841
842         mywindow_init_mainwin(mainwin, orx, ory, sizex, sizey);
843         resize_screens(orx, ory, sizex, sizey);
844 }
845
846 /***/
847
848 static short afterqueue[MAXQUEUE][3];
849 static int nafterqitems= 0;
850
851 void addafterqueue(short win, unsigned short evt, short val)
852 {
853         if (nafterqitems<MAXQUEUE) {
854                 int a;
855                 
856                 /* only one afterqueue event of each type */
857                 for(a=0; a<nafterqitems; a++) {
858                         if(afterqueue[a][0]==win && afterqueue[a][1]==evt) {
859                                 afterqueue[a][2]= val;
860                                 return;
861                         }
862                 }
863                 afterqueue[nafterqitems][0]= win;
864                 afterqueue[nafterqitems][1]= evt;
865                 afterqueue[nafterqitems][2]= val;
866                 nafterqitems++;
867         }
868 }
869
870 static void append_afterqueue(void)
871 {
872         while (nafterqitems) {
873                 short win= afterqueue[nafterqitems-1][0];
874                 unsigned short evt= afterqueue[nafterqitems-1][1];
875                 short val= afterqueue[nafterqitems-1][2];
876
877                 addqueue(win, evt, val);
878                 
879                 nafterqitems--;
880         }
881 }
882
883 /* check for event in afterqueue, used in force_draw in space.c */
884 int afterqtest(short win, unsigned short evt)
885 {
886         int a;
887         
888         for(a=0; a<nafterqitems; a++) {
889                 if(afterqueue[a][0]==win && afterqueue[a][1]==evt) return 1;
890         }
891         return 0;
892 }
893
894
895 static char ext_load_str[256]= {0, 0};
896
897 static short ext_reshape= 0, ext_redraw=0, ext_inputchange=0, ext_mousemove=0, ext_undopush=0;
898
899 static void flush_extqd_events(void) {
900         if (ext_inputchange) {
901                 mainqenter(INPUTCHANGE, ext_inputchange);
902         } else if (ext_reshape) {
903                 mainqenter(RESHAPE, ext_redraw);
904         } else if (ext_redraw) {
905                 mainqenter(REDRAW, ext_redraw);
906         } else if (ext_undopush) {
907                 mainqenter(UNDOPUSH, ext_undopush);
908         } else if (ext_mousemove) {
909                 short mouse[2];
910                 
911                 getmouseco_sc(mouse);
912                 
913                 mainqenter(MOUSEX, mouse[0]);
914                 mainqenter(MOUSEY, mouse[1]);
915         }
916         
917         ext_inputchange= ext_reshape= ext_redraw= ext_mousemove= ext_undopush= 0;
918 }
919
920 int qtest(void)
921 {
922         if (!mainqtest()) {
923                 winlay_process_events(0);
924         }
925         
926         return mainqtest();
927 }
928
929         /* return true if events are waiting anywhere */
930 int anyqtest(void)
931 {
932         ScrArea *sa;
933
934         if (nafterqitems || qtest()) return 1;
935
936         for (sa= G.curscreen->areabase.first; sa; sa= sa->next) {
937                 if (bwin_qtest(sa->win)) return 1;
938                 if (sa->headwin && bwin_qtest(sa->headwin)) return 1;
939         }
940
941         return 0;
942 }
943
944 static void wait_for_event(void)
945 {
946         while (!mainqtest()) {
947                 winlay_process_events(1);
948         }
949 }
950
951 unsigned short screen_qread(short *val, char *ascii)
952 {
953         unsigned short event;
954
955         wait_for_event();
956
957         event= mainqread(val, ascii);
958         
959         if(event==RIGHTSHIFTKEY || event==LEFTSHIFTKEY) {
960                 if(*val) G.qual |= LR_SHIFTKEY;
961                 else G.qual &= ~LR_SHIFTKEY;
962         }
963         else if(event==RIGHTALTKEY || event==LEFTALTKEY) {
964                 if(*val) G.qual |= LR_ALTKEY;
965                 else G.qual &= ~LR_ALTKEY;
966         }
967         else if(event==RIGHTCTRLKEY || event==LEFTCTRLKEY) {
968                 if(*val) G.qual |= LR_CTRLKEY;
969                 else G.qual &= ~LR_CTRLKEY;
970         }
971         else if(event==COMMANDKEY) {            // OSX
972                 if(*val) G.qual |= LR_COMMANDKEY;
973                 else G.qual &= ~LR_COMMANDKEY;
974         }
975
976         return event;
977 }
978
979 unsigned short extern_qread_ext(short *val, char *ascii)
980 {
981         /* stores last INPUTCHANGE and last REDRAW */
982         unsigned short event;
983         
984         event= screen_qread(val, ascii);
985         if(event==RESHAPE) ext_reshape= *val;
986         else if(event==REDRAW) ext_redraw= *val;
987         else if(event==UNDOPUSH) ext_undopush= *val;
988         else if(event==INPUTCHANGE) ext_inputchange= *val;
989         else if(event==MOUSEY || event==MOUSEX) ext_mousemove= 1;
990         else if((G.qual & (LR_CTRLKEY|LR_ALTKEY)) && event==F3KEY) {
991                 if(*val) {
992                         BIF_screendump(0);
993                         return ESCKEY;  /* go out of menu, if that was set */
994                 }
995         }
996
997         return event;
998 }
999 unsigned short extern_qread(short *val)
1000 {
1001         char ascii;
1002         return extern_qread_ext(val, &ascii);
1003 }
1004
1005 int blender_test_break(void)
1006 {
1007         if (!G.background) {
1008                 static double ltime= 0;
1009                 double curtime= PIL_check_seconds_timer();
1010
1011                         /* only check for breaks every 10 milliseconds
1012                          * if we get called more often.
1013                          */
1014                 if ((curtime-ltime)>.001) {
1015                         ltime= curtime;
1016
1017                         while(qtest()) {
1018                                 short val;
1019                                 if (extern_qread(&val) == ESCKEY) {
1020                                         G.afbreek= 1;
1021                                 }
1022                         }
1023                 }
1024         }
1025
1026         return (G.afbreek==1);
1027 }
1028
1029 void reset_autosave(void) 
1030 {
1031         if(U.flag & USER_AUTOSAVE) {
1032                 window_set_timer(mainwin, U.savetime*60*1000, AUTOSAVE_FILE);
1033         }
1034 }
1035
1036 /* ************ handlers ************** */
1037
1038 /* don't know yet how the handlers will evolve, for simplicity
1039 i choose for an array with eventcodes, this saves in a file!
1040 */
1041 void add_screenhandler(bScreen *sc, short eventcode, short val)
1042 {
1043         short a;
1044         
1045         // find empty spot
1046         for(a=0; a<SCREEN_MAXHANDLER; a+=2) {
1047                 if( sc->handler[a]==eventcode ) {
1048                         sc->handler[a+1]= val;
1049                         break;
1050                 }
1051                 else if( sc->handler[a]==0) {
1052                         sc->handler[a]= eventcode;
1053                         sc->handler[a+1]= val;
1054                         break;
1055                 }
1056         }
1057         if(a==SCREEN_MAXHANDLER) printf("error; max (4) screen handlers reached!\n");
1058 }
1059
1060 void rem_screenhandler(bScreen *sc, short eventcode)
1061 {
1062         short a;
1063         
1064         for(a=0; a<SCREEN_MAXHANDLER; a+=2) {
1065                 if( sc->handler[a]==eventcode) {
1066                         sc->handler[a]= 0;
1067                         break;
1068                 }
1069         }
1070 }
1071
1072 int has_screenhandler(bScreen *sc, short eventcode)
1073 {
1074         short a;
1075         
1076         for(a=0; a<SCREEN_MAXHANDLER; a+=2) {
1077                 if( sc->handler[a]==eventcode) {
1078                         return 1;
1079                 }
1080         }
1081         return 0;
1082 }
1083
1084 static void animated_screen(bScreen *sc, short val)
1085 {
1086         if ((val & TIME_WITH_SEQ_AUDIO)) {
1087                 if(CFRA>=PEFRA) {
1088                         CFRA= PSFRA;
1089                         audiostream_stop();
1090                         audiostream_start( CFRA );
1091                 }
1092                 else {
1093                         int cfra = audiostream_pos();
1094                         if(cfra <= CFRA) CFRA++;
1095                         else CFRA= cfra;
1096                 }
1097         }
1098         else {
1099                 CFRA++;
1100                 if(CFRA > PEFRA) CFRA= PSFRA;
1101         }
1102         
1103         update_for_newframe_nodraw(1);
1104         
1105         if(val & TIME_ALL_3D_WIN)
1106                 allqueue(REDRAWVIEW3D, 0);
1107         else if(val & TIME_LEFTMOST_3D_WIN) {
1108                 ScrArea *sa= sc->areabase.first, *samin=NULL;
1109                 int min= 10000;
1110                 for(; sa; sa= sa->next) {
1111                         if(sa->spacetype==SPACE_VIEW3D) {
1112                                 if(sa->winrct.xmin - sa->winrct.ymin < min) {
1113                                         samin= sa;
1114                                         min= sa->winrct.xmin - sa->winrct.ymin;
1115                                 }
1116                         }
1117                 }
1118                 if(samin) scrarea_queue_winredraw(samin);
1119         }
1120         if(val & TIME_ALL_ANIM_WIN) allqueue(REDRAWANIM, 0);
1121         if(val & TIME_ALL_BUTS_WIN) allqueue(REDRAWBUTSALL, 0);
1122         if(val & TIME_SEQ) {
1123                 allqueue(REDRAWSEQ, 0);
1124         }
1125         
1126         allqueue(REDRAWTIME, 0);
1127 }
1128
1129 /* because we still have to cope with subloops, this function is called
1130 in viewmove() for example too */
1131
1132 /* returns 1 if something was handled */
1133 /* restricts to frames-per-second setting for frequency of updates */
1134 int do_screenhandlers(bScreen *sc)
1135 {
1136         static double ltime=0.0;
1137         double swaptime, time;
1138         short a, done= 0;
1139         
1140         time = PIL_check_seconds_timer();
1141         swaptime= 1.0/FPS;
1142         
1143         /* only now do the handlers */
1144         if(swaptime < time-ltime || ltime==0.0) {
1145                 
1146                 ltime= time;
1147
1148                 for(a=0; a<SCREEN_MAXHANDLER; a+=2) {
1149                         switch(sc->handler[a]) {
1150                                 case SCREEN_HANDLER_ANIM:
1151                                         animated_screen(sc, sc->handler[a+1]);
1152                                         done= 1;
1153                                         break;
1154                                 case SCREEN_HANDLER_PYTHON:
1155                                         done= 1;
1156                                         break;
1157                                 case SCREEN_HANDLER_VERSE:
1158 #ifdef WITH_VERSE
1159                                         b_verse_update();
1160 #endif
1161
1162                                         done= 1;
1163                                         break;
1164                         }
1165                 }
1166         }
1167         else if( qtest()==0) PIL_sleep_ms(5);   // 5 milliseconds pause, for idle
1168
1169         /* separate check for if we need to add to afterqueue */
1170         /* is only to keep mainqueue awqke */
1171         for(a=0; a<SCREEN_MAXHANDLER; a+=2) {
1172                 if(sc->handler[a]) {
1173                         ScrArea *sa= sc->areabase.first;
1174                         if(sa->headwin) addafterqueue(sa->headwin, SCREEN_HANDLER, 1);
1175                         else addafterqueue(sa->win, SCREEN_HANDLER, 1);
1176                 }
1177         }
1178         
1179         return done;
1180 }
1181
1182 /* ****** end screen handlers ************ */
1183
1184 static void drawscreen(void)
1185 {
1186         ScrArea *sa;
1187         
1188         mywinset(G.curscreen->mainwin);
1189         myortho2(-0.375, (float)G.curscreen->sizex-0.375, -0.375, (float)G.curscreen->sizey-0.375);
1190         
1191         sa= G.curscreen->areabase.first;
1192         while(sa) {
1193                 drawscredge_area(sa);
1194                 sa= sa->next;
1195         }
1196         
1197         /* this double draw patch seems to be needed for certain sgi's (octane, indigo2) */
1198 #if defined(__sgi) || defined(__sun__) || defined( __sun ) || defined (__sparc) || defined (__sparc__)
1199         glDrawBuffer(GL_FRONT);
1200         
1201         sa= G.curscreen->areabase.first;
1202         while(sa) {
1203                 drawscredge_area(sa);
1204                 sa= sa->next;
1205         }
1206         
1207         glDrawBuffer(GL_BACK);
1208 #endif
1209 }
1210
1211 static void screen_dispatch_events(void) {
1212         int events_remaining= 1;
1213         ScrArea *sa;
1214
1215         window_make_active(mainwin); // added it here instead of screenmain (ton)
1216
1217         while (events_remaining) {
1218                 events_remaining= 0;
1219                                 
1220                 winqueue_break= 0;
1221                 for (sa= G.curscreen->areabase.first; sa; sa= sa->next) {
1222                                 /* first check header, then rest. Header sometimes has initialization code */
1223                         if (sa->headwin && bwin_qtest(sa->headwin)) {
1224                                 scrarea_dispatch_header_events(sa);
1225                                 events_remaining= 1;
1226                         }
1227                         if (winqueue_break) break;
1228
1229                         if (bwin_qtest(sa->win)) {
1230                                 scrarea_dispatch_events(sa);
1231                                 events_remaining= 1;
1232                         }
1233                         if (winqueue_break) break;
1234                 }
1235
1236                 if (winqueue_break) break;
1237         }
1238
1239         /* winqueue_break isnt the best of all solutions... but it is called on switching screens,
1240                 so drawing should wait for all redraw/init events to be handled */
1241         if (winqueue_break==0) {
1242                 if (dodrawscreen) {
1243                         drawscreen();
1244                         dodrawscreen= 0;
1245                 }
1246                 
1247                 screen_swapbuffers();
1248                 do_screenhandlers(G.curscreen);
1249         }
1250 }
1251
1252 static ScrArea *screen_find_area_for_pt(bScreen *sc, short *mval) 
1253 {
1254         ScrArea *sa;
1255         
1256         /* hotspot area of 1 pixel extra */
1257         
1258         for (sa= sc->areabase.first; sa; sa= sa->next) {
1259                 if( sa->totrct.xmin + 1 < mval[0] )
1260                         if( sa->totrct.ymin + 1 < mval[1] )
1261                                 if( sa->totrct.xmax - 1 > mval[0] )
1262                                         if( sa->totrct.ymax - 1 > mval[1] )
1263                                                 return sa;
1264         }
1265         return NULL;
1266 }
1267
1268 /* ugly yah, will disappear on better event system */
1269 /* is called from interface.c after button events */
1270 static char delayed_undo_name[64];
1271 void screen_delayed_undo_push(char *name)
1272 {
1273         strncpy(delayed_undo_name, name, 63);
1274         mainqenter(UNDOPUSH, 1);
1275 }
1276
1277 void screenmain(void)
1278 {
1279         int has_input= 1;
1280         int firsttime = 1;
1281         int onload_script = 0;
1282
1283         window_make_active(mainwin);
1284         
1285         while (1) {
1286                 unsigned short event;
1287                 short val, towin;
1288                 char ascii;
1289
1290                 flush_extqd_events();
1291                 if (nafterqitems && !qtest()) {
1292                         append_afterqueue();
1293                         event= val= ascii= 0;
1294                 } else {
1295                         event= screen_qread(&val, &ascii);
1296                 }
1297                 
1298                 // window_make_active(mainwin); // (only for inputchange, removed, (ton))
1299
1300                 if (event==INPUTCHANGE) {
1301                         window_make_active(mainwin);
1302                         G.qual= get_qual();
1303                 }
1304                 
1305                         /* If the main window is active, find the current active ScrArea
1306                          * underneath the mouse cursor, updating the headers & cursor for
1307                          * the appropriate internal window if things have changed.
1308                          * 
1309                          * If the main window is not active, deactivate the internal 
1310                          * window.
1311                          */
1312                 if (has_input || g_activearea==NULL || G.curscreen->winakt) {
1313                         ScrArea *newactarea;
1314                         int newactwin;
1315                         short mval[2];
1316
1317                         getmouseco_sc(mval);
1318                         newactarea= screen_find_area_for_pt(G.curscreen, mval);                 
1319
1320                         if (newactarea) {
1321                                 if (BLI_in_rcti(&newactarea->headrct, mval[0], mval[1])) {
1322                                         newactwin= newactarea->headwin;
1323                                         set_cursor(CURSOR_STD);
1324                                 } else {
1325                                         newactwin= newactarea->win;
1326                                 }
1327                         } else {
1328                                 newactwin= 0;
1329                         }
1330
1331                         if (newactarea && (newactarea != g_activearea)) {
1332                                 if (g_activearea) scrarea_queue_headredraw(g_activearea);
1333                                 scrarea_queue_headredraw(newactarea);
1334                                 if (!(BLI_in_rcti(&newactarea->headrct, mval[0], mval[1]))) /* header always gets std cursor */
1335                                         set_cursor(newactarea->cursor);
1336                                 g_activearea= newactarea;
1337                         }
1338                         /* when you move mouse from header to window, buttons can remain hilited otherwise */
1339                         if(newactwin != G.curscreen->winakt) {
1340                                 if (g_activearea) scrarea_queue_headredraw(g_activearea);
1341                         }
1342                         G.curscreen->winakt= newactwin;
1343                         
1344                         if (G.curscreen->winakt) {
1345                                 areawinset(G.curscreen->winakt);
1346                                 if (!(BLI_in_rcti(&newactarea->headrct, mval[0], mval[1]))) /* header always gets std cursor */
1347                                         set_cursor(choose_cursor(g_activearea));
1348                         }
1349                 } 
1350                 else {
1351                         if (g_activearea) {
1352                                 scrarea_queue_headredraw(g_activearea);
1353                         }
1354                         g_activearea= NULL;
1355                         G.curscreen->winakt= 0;
1356                 }
1357
1358                 towin= 0;
1359                 if (event==WINCLOSE) {
1360                         exit_usiblender();
1361                 } 
1362                 else if (event==DRAWEDGES) {
1363                         dodrawscreen= 1;
1364                 }
1365                 else if (event==RESHAPE) {
1366                         init_mainwin();
1367                         markdirty_all();
1368                         dodrawscreen= 1;
1369                 }
1370                 else if (event==REDRAW) {
1371                         markdirty_all();
1372                         dodrawscreen= 1;
1373                 }
1374                 else if( event==UNDOPUSH) {
1375                         BIF_undo_push(delayed_undo_name);
1376                 }
1377                 else if (event==AUTOSAVE_FILE) {
1378                         BIF_write_autosave();
1379                 }
1380                 else if (event==LOAD_FILE) {
1381                         BIF_read_file(ext_load_str);
1382                         sound_initialize_sounds();
1383                 }
1384 #ifndef DISABLE_PYTHON
1385                 else if ((event==ONLOAD_SCRIPT) && BPY_has_onload_script()) {
1386                         /* event queued in setup_app_data() in blender.c, where G.f is checked */
1387                         onload_script = 1;
1388                         firsttime = 1; /* see last 'if' in this function */
1389                 }
1390 #endif
1391                 else {
1392                         towin= 1;
1393                 }
1394
1395                 if (!g_activearea) {
1396                         towin= 0;
1397                 }
1398                 else if (event==QKEY) {
1399                         /* Temp place to print mem debugging info ctrl+alt+shift + qkey */
1400                         if ( G.qual == (LR_SHIFTKEY | LR_ALTKEY | LR_CTRLKEY) ) {
1401                                 MEM_printmemlist_stats();
1402                         }
1403                         
1404                         else if((G.obedit && G.obedit->type==OB_FONT && g_activearea->spacetype==SPACE_VIEW3D)||g_activearea->spacetype==SPACE_TEXT||g_activearea->spacetype==SPACE_SCRIPT);
1405                         else {
1406                                 if(val && (G.qual == LR_CTRLKEY)) {
1407                                         if(okee("Quit Blender")) exit_usiblender();
1408                                 }
1409                                 towin= 0;
1410                         }
1411                 }
1412                 else if (event==RIGHTARROWKEY) {
1413                         if(textediting==0 && val && (G.qual & LR_CTRLKEY)) {
1414                                 bScreen *sc= G.curscreen->id.next;
1415
1416                                 /* if screen is last, set it to first */
1417                                 if(sc == NULL) 
1418                                         sc= G.main->screen.first;
1419                                 
1420                                 if(is_allowed_to_change_screen(sc)) setscreen(sc);
1421                                 g_activearea= NULL;
1422                                 towin= 0;
1423                         }
1424                 }
1425                 else if (event==LEFTARROWKEY) {
1426                         if(textediting==0 && val && (G.qual & LR_CTRLKEY)) {
1427                                 bScreen *sc= G.curscreen->id.prev;
1428                                 
1429                                 /* if screen is first, set it to last */
1430                                 if(sc == NULL) 
1431                                         sc= G.main->screen.last;
1432                                 
1433                                 if(is_allowed_to_change_screen(sc)) setscreen(sc);
1434                                 g_activearea= NULL;
1435                                 towin= 0;
1436                         }
1437                 }
1438                 else if (!G.curscreen->winakt) {
1439                         ScrEdge *actedge;
1440                         short mval[2];
1441
1442                         getmouseco_sc(mval);
1443                         actedge= screen_find_active_scredge(G.curscreen, mval);
1444
1445                         if (actedge) {
1446                                 if (scredge_is_horizontal(actedge)) {
1447                                         set_cursor(CURSOR_Y_MOVE);
1448                                 } else {
1449                                         set_cursor(CURSOR_X_MOVE);
1450                                 }
1451                                 // this does global hotkeys too
1452                                 screen_edge_edit_event(g_activearea, actedge, event, val);
1453                         } else {
1454                                 set_cursor(CURSOR_STD);
1455                         }
1456                         
1457                         towin= 0;
1458                 }
1459                 else if (event==ZKEY) {
1460                         if(val && G.qual==(LR_ALTKEY|LR_SHIFTKEY|LR_CTRLKEY)) {
1461                                 extern void set_debug_swapbuffers_ovveride(bScreen *sc, int mode);
1462
1463                                 int which= pupmenu("Swapbuffers%t|Simple|Debug|DebugSwap|Redraw|Default|KillSwap");
1464                                         
1465                                 switch (which) {
1466                                 case 1: set_debug_swapbuffers_ovveride(G.curscreen, 's'); break;
1467                                 case 2: set_debug_swapbuffers_ovveride(G.curscreen, 'd'); break;
1468                                 case 3: set_debug_swapbuffers_ovveride(G.curscreen, 'f'); break;
1469                                 case 4: set_debug_swapbuffers_ovveride(G.curscreen, 'r'); break;
1470                                 case 5: set_debug_swapbuffers_ovveride(G.curscreen, 0); break;
1471                                 case 6: 
1472                                         if (g_activearea) {
1473                                                 g_activearea->head_swap= 0;
1474                                                 g_activearea->win_swap= 0;
1475                                         }
1476                                         break;
1477                                 }
1478                                 towin= 0;
1479                         }
1480                 }
1481                 else if (event==SPACEKEY) {
1482                         if ((g_activearea->spacetype!=SPACE_TEXT) &&
1483                                 ( !((g_activearea->spacetype==SPACE_VIEW3D) && ((G.obedit) && G.obedit->type==OB_FONT)) ) &&
1484                                 val && 
1485                                 (G.qual & LR_SHIFTKEY)) {
1486                                         area_fullscreen();
1487                                         g_activearea= NULL;
1488                                         towin= 0;
1489                         }
1490                         else {
1491                                 if((G.obedit && G.obedit->type==OB_FONT && g_activearea->spacetype==SPACE_VIEW3D)||g_activearea->spacetype==SPACE_TEXT||g_activearea->spacetype==SPACE_SCRIPT||g_activearea->spacetype==SPACE_SEQ);
1492                                 else if(G.qual==0) {
1493                                         if(val) toolbox_n();
1494                                         towin= 0;
1495                                 }
1496                         }
1497                 }
1498                 else if(ELEM(event, UPARROWKEY, DOWNARROWKEY)) {
1499                         if(val && (G.qual & LR_CTRLKEY)) {
1500                                 area_fullscreen();
1501                                 g_activearea= NULL;
1502                                 towin= 0;
1503                         }
1504                 }
1505
1506                 if (towin && event) {
1507                         if (blenderqread(event, val))   // the global keys
1508                                 addqueue_ext(G.curscreen->winakt, event, val, ascii);
1509                 }
1510
1511                         /* only process subwindow queue's once the
1512                          * main queue has been emptyied.
1513                          */
1514                 event= qtest();
1515                 if (event==0 || event==EXECUTE) {
1516                         screen_dispatch_events();
1517                 }
1518                 
1519                 if(G.f & G_DEBUG) {
1520                         GLenum error = glGetError();
1521                         if (error)
1522                                 printf("GL error: %s\n", gluErrorString(error));
1523                 }
1524                 /* Bizar hack. The event queue has mutated... */
1525                 if ( (firsttime) && (event == 0) ) {
1526 #ifndef DISABLE_PYTHON
1527                         if (onload_script) {
1528                                 /* OnLoad scriptlink */
1529                                 BPY_do_pyscript(&G.scene->id, SCRIPT_ONLOAD);
1530                                 onload_script = 0;
1531                         } else
1532 #endif
1533                         if (G.fileflags & G_FILE_AUTOPLAY) {
1534                                 // SET AUTOPLAY in G.flags for
1535                                 // other fileloads
1536
1537                                 G.flags |= G_FILE_AUTOPLAY;
1538                                 area_autoplayscreen();
1539
1540                                 // Let The Games Begin
1541                                 // fake a 'p' keypress
1542
1543                                 mainqenter(PKEY, 1);
1544                         } else {
1545                                 extern char datatoc_splash_jpg[];
1546                                 extern int datatoc_splash_jpg_size;
1547
1548                                 //if (! ((G.main->versionfile >= G.version)
1549                                 //       || G.save_over)) {
1550                                         splash((void *)datatoc_splash_jpg,
1551                                                datatoc_splash_jpg_size, NULL);
1552                                 //}
1553                         }
1554                         firsttime = 0;
1555                 }
1556         }
1557 }
1558
1559 #if 0
1560 //#ifdef _WIN32 // FULLSCREEN
1561 void mainwindow_toggle_fullscreen(int fullscreen)
1562 {
1563         if (fullscreen) U.uiflag |= USER_FLIPFULLSCREEN;
1564         else U.uiflag &= ~USER_FLIPFULLSCREEN;
1565
1566         window_toggle_fullscreen(mainwin, fullscreen);
1567 }
1568 #endif
1569
1570 void mainwindow_raise(void) 
1571 {
1572         if(mainwin)
1573                 window_raise(mainwin);
1574 }
1575
1576 void mainwindow_make_active(void) 
1577 {
1578         if(mainwin)
1579                 window_make_active(mainwin);
1580 }
1581
1582 void mainwindow_close(void) 
1583 {
1584         if(mainwin)
1585                 window_destroy(mainwin);
1586         mainwin= NULL;
1587 }
1588
1589 void mainwindow_set_filename_to_title(char *filename)
1590 {
1591         char str[FILE_MAXDIR + FILE_MAXFILE];
1592         char dir[FILE_MAXDIR];
1593         char file[FILE_MAXFILE];
1594
1595         BLI_split_dirfile_basic(filename, dir, file);
1596
1597         if(BLI_streq(file, ".B.blend") || filename[0] =='\0')
1598                 sprintf(str, "Blender");
1599         else
1600                 sprintf(str, "Blender [%s]", filename);
1601
1602         window_set_title(mainwin, str);
1603 }
1604
1605 /* *********  AREAS  ************* */
1606
1607 void setprefsize(int stax, int stay, int sizx, int sizy, int maximized)
1608 {
1609         int scrwidth, scrheight;
1610         
1611         winlay_get_screensize(&scrwidth, &scrheight);
1612                 
1613         if(sizx<320) sizx= 320;
1614         if(sizy<256) sizy= 256;
1615
1616         if(stay+sizy>scrheight) {
1617                 fprintf(stderr," height prob \n");
1618                 sizy= scrheight-stay;
1619         }
1620
1621         if(sizx<320 || sizy<256) {
1622                 printf("ERROR: illegal prefsize\n");
1623                 return;
1624         }
1625         
1626         prefstax= stax;
1627         prefstay= stay;
1628         prefsizx= sizx;
1629         prefsizy= sizy;
1630
1631         start_maximized= maximized;
1632 }
1633
1634
1635 static ScrVert *screen_addvert(bScreen *sc, short x, short y)
1636 {
1637         ScrVert *sv= MEM_callocN(sizeof(ScrVert), "addscrvert");
1638         sv->vec.x= x;
1639         sv->vec.y= y;
1640         
1641         BLI_addtail(&sc->vertbase, sv);
1642         return sv;
1643 }
1644
1645 static void sortscrvert(ScrVert **v1, ScrVert **v2)
1646 {
1647         ScrVert *tmp;
1648         
1649         if (*v1 > *v2) {
1650                 tmp= *v1;
1651                 *v1= *v2;
1652                 *v2= tmp;       
1653         }
1654 }
1655
1656 static ScrEdge *screen_addedge(bScreen *sc, ScrVert *v1, ScrVert *v2)
1657 {
1658         ScrEdge *se= MEM_callocN(sizeof(ScrEdge), "addscredge");
1659
1660         sortscrvert(&v1, &v2);
1661         se->v1= v1;
1662         se->v2= v2;
1663         
1664         BLI_addtail(&sc->edgebase, se);
1665         return se;
1666 }
1667
1668 static ScrEdge *screen_findedge(bScreen *sc, ScrVert *v1, ScrVert *v2)
1669 {
1670         ScrEdge *se;
1671
1672         sortscrvert(&v1, &v2);
1673         for (se= sc->edgebase.first; se; se= se->next)
1674                 if(se->v1==v1 && se->v2==v2)
1675                         return se;
1676
1677         return NULL;
1678 }
1679
1680 static void removedouble_scrverts(void)
1681 {
1682         ScrVert *v1, *verg;
1683         ScrEdge *se;
1684         ScrArea *sa;
1685         
1686         verg= G.curscreen->vertbase.first;
1687         while(verg) {
1688                 if(verg->newv==0) {     /* !!! */
1689                         v1= verg->next;
1690                         while(v1) {
1691                                 if(v1->newv==0) {       /* !?! */
1692                                         if(v1->vec.x==verg->vec.x && v1->vec.y==verg->vec.y) {
1693                                                 /* printf("doublevert\n"); */
1694                                                 v1->newv= verg;
1695                                         }
1696                                 }
1697                                 v1= v1->next;
1698                         }
1699                 }
1700                 verg= verg->next;
1701         }
1702         
1703         /* replace pointers in edges and faces */
1704         se= G.curscreen->edgebase.first;
1705         while(se) {
1706                 if(se->v1->newv) se->v1= se->v1->newv;
1707                 if(se->v2->newv) se->v2= se->v2->newv;
1708                 /* edges changed: so.... */
1709                 sortscrvert(&(se->v1), &(se->v2));
1710                 se= se->next;
1711         }
1712         sa= G.curscreen->areabase.first;
1713         while(sa) {
1714                 if(sa->v1->newv) sa->v1= sa->v1->newv;
1715                 if(sa->v2->newv) sa->v2= sa->v2->newv;
1716                 if(sa->v3->newv) sa->v3= sa->v3->newv;
1717                 if(sa->v4->newv) sa->v4= sa->v4->newv;
1718                 sa= sa->next;
1719         }
1720         
1721         /* remove */
1722         verg= G.curscreen->vertbase.first;
1723         while(verg) {
1724                 v1= verg->next;
1725                 if(verg->newv) {
1726                         BLI_remlink(&G.curscreen->vertbase, verg);
1727                         MEM_freeN(verg);
1728                 }
1729                 verg= v1;
1730         }
1731         
1732 }
1733
1734 static void removenotused_scrverts(void)
1735 {
1736         ScrVert *sv, *svn;
1737         ScrEdge *se;
1738
1739         /* we assume edges are ok */
1740         
1741         se= G.curscreen->edgebase.first;
1742         while(se) {
1743                 se->v1->flag= 1;
1744                 se->v2->flag= 1;
1745                 se= se->next;
1746         }
1747         
1748         sv= G.curscreen->vertbase.first;
1749         while(sv) {
1750                 svn= sv->next;
1751                 if(sv->flag==0) {
1752                         BLI_remlink(&G.curscreen->vertbase, sv);
1753                         MEM_freeN(sv);
1754                 }
1755                 else sv->flag= 0;
1756                 sv= svn;
1757         }
1758 }
1759
1760 static void removedouble_scredges(void)
1761 {
1762         ScrEdge *verg, *se, *sn;
1763         
1764         /* compare */
1765         verg= G.curscreen->edgebase.first;
1766         while(verg) {
1767                 se= verg->next;
1768                 while(se) {
1769                         sn= se->next;
1770                         if(verg->v1==se->v1 && verg->v2==se->v2) {
1771                                 BLI_remlink(&G.curscreen->edgebase, se);
1772                                 MEM_freeN(se);
1773                         }
1774                         se= sn;
1775                 }
1776                 verg= verg->next;
1777         }
1778 }
1779
1780 static void removenotused_scredges(void)
1781 {
1782         ScrEdge *se, *sen;
1783         ScrArea *sa;
1784         int a=0;
1785         
1786         /* sets flags when edge is used in area */
1787         sa= G.curscreen->areabase.first;
1788         while(sa) {
1789                 se= screen_findedge(G.curscreen, sa->v1, sa->v2);
1790                 if(se==0) printf("error: area %d edge 1 bestaat niet\n", a);
1791                 else se->flag= 1;
1792                 se= screen_findedge(G.curscreen, sa->v2, sa->v3);
1793                 if(se==0) printf("error: area %d edge 2 bestaat niet\n", a);
1794                 else se->flag= 1;
1795                 se= screen_findedge(G.curscreen, sa->v3, sa->v4);
1796                 if(se==0) printf("error: area %d edge 3 bestaat niet\n", a);
1797                 else se->flag= 1;
1798                 se= screen_findedge(G.curscreen, sa->v4, sa->v1);
1799                 if(se==0) printf("error: area %d edge 4 bestaat niet\n", a);
1800                 else se->flag= 1;
1801                 sa= sa->next;
1802                 a++;
1803         }
1804         se= G.curscreen->edgebase.first;
1805         while(se) {
1806                 sen= se->next;
1807                 if(se->flag==0) {
1808                         BLI_remlink(&G.curscreen->edgebase, se);
1809                         MEM_freeN(se);
1810                 }
1811                 else se->flag= 0;
1812                 se= sen;
1813         }
1814 }
1815
1816 void calc_arearcts(ScrArea *sa)
1817 {
1818
1819         if(sa->v1->vec.x>0) sa->totrct.xmin= sa->v1->vec.x+1;
1820         else sa->totrct.xmin= sa->v1->vec.x;
1821         if(sa->v4->vec.x<G.curscreen->sizex-1) sa->totrct.xmax= sa->v4->vec.x-1;
1822         else sa->totrct.xmax= sa->v4->vec.x;
1823         
1824         if(sa->v1->vec.y>0) sa->totrct.ymin= sa->v1->vec.y+1;
1825         else sa->totrct.ymin= sa->v1->vec.y;
1826         if(sa->v2->vec.y<G.curscreen->sizey-1) sa->totrct.ymax= sa->v2->vec.y-1;
1827         else sa->totrct.ymax= sa->v2->vec.y;
1828         
1829         sa->winrct= sa->totrct;
1830         sa->headrct= sa->totrct;
1831         if(sa->headertype) {
1832                 if(sa->headertype==HEADERDOWN) {
1833                         sa->headrct.ymax= sa->headrct.ymin+HEADERY;
1834                         sa->winrct.ymin= sa->headrct.ymax+1;
1835                 }
1836                 else if(sa->headertype==HEADERTOP) {
1837                         sa->headrct.ymin= sa->headrct.ymax-HEADERY;
1838                         sa->winrct.ymax= sa->headrct.ymin-1;
1839                 }
1840         }
1841         else {
1842                 sa->headrct.ymax= sa->headrct.ymin;
1843         }
1844         if(sa->winrct.ymin>sa->winrct.ymax) sa->winrct.ymin= sa->winrct.ymax;
1845         
1846         /* for speedup */
1847         sa->winx= sa->winrct.xmax-sa->winrct.xmin+1;
1848         sa->winy= sa->winrct.ymax-sa->winrct.ymin+1;
1849 }
1850
1851 static void openheadwin(ScrArea *sa)
1852 {
1853         sa->headwin= myswinopen(G.curscreen->mainwin,
1854                 sa->headrct.xmin, sa->headrct.xmax, sa->headrct.ymin, sa->headrct.ymax);
1855
1856         glMatrixMode(GL_MODELVIEW);
1857         
1858         areawinar[sa->headwin]= sa;     /* otherwise addqueue does not work */
1859         
1860         scrarea_do_headchange(sa);      /* headchange is no callback, apply right away. this is for render-to-imagewindow... this can be called on startup by sequencer, which invokes redraw before all events are handled. bad stuff... */
1861         addqueue(sa->headwin, CHANGED, 1);
1862 }
1863
1864 static void openareawin(ScrArea *sa)
1865 {
1866         sa->win= myswinopen(G.curscreen->mainwin, 
1867                 sa->winrct.xmin, sa->winrct.xmax, sa->winrct.ymin, sa->winrct.ymax);
1868
1869         areawinar[sa->win]= sa; /* otherwise addqueue does not work */
1870         addqueue(sa->win, CHANGED, 1);
1871 }
1872
1873 static void closeheadwin(ScrArea *sa)
1874 {
1875         if(sa->headwin) mywinclose(sa->headwin);
1876         sa->headwin= 0;
1877 }
1878
1879 static void closeareawin(ScrArea *sa)
1880 {
1881         uiFreeBlocksWin(&sa->uiblocks, sa->win);
1882         
1883         if(sa->win) mywinclose(sa->win);
1884         sa->win= 0;
1885 }
1886
1887 static void del_area(ScrArea *sa)
1888 {
1889         closeareawin(sa);
1890         closeheadwin(sa);
1891
1892         freespacelist(sa);
1893         
1894         uiFreeBlocks(&sa->uiblocks);
1895         uiFreePanels(&sa->panels);
1896 #ifndef DISABLE_PYTHON
1897         BPY_free_scriptlink(&sa->scriptlink);
1898 #endif  
1899         if(sa==curarea) curarea= NULL;
1900         if(sa==g_activearea) g_activearea= NULL;
1901 }
1902
1903 /* sa2 to sa1, we swap spaces for fullscreen to keep all allocated data */
1904 static void copy_areadata(ScrArea *sa1, ScrArea *sa2, int swap_space)
1905 {
1906         Panel *pa1, *pa2, *patab;
1907         ScriptLink *slink1 = &sa1->scriptlink, *slink2 = &sa2->scriptlink;
1908
1909         sa1->headertype= sa2->headertype;
1910         sa1->spacetype= sa2->spacetype;
1911         Mat4CpyMat4(sa1->winmat, sa2->winmat);
1912
1913         if(swap_space) {
1914                 SWAP(ListBase, sa1->spacedata, sa2->spacedata);
1915                 /* exception: ensure preview is reset */
1916                 if(sa1->spacetype==SPACE_VIEW3D)
1917                         BIF_view3d_previewrender_free(sa1->spacedata.first);
1918         }
1919         else {
1920                 freespacelist(sa1);
1921                 duplicatespacelist(sa1, &sa1->spacedata, &sa2->spacedata);
1922         }
1923         
1924         BLI_freelistN(&sa1->panels);
1925         duplicatelist(&sa1->panels, &sa2->panels);
1926
1927         /* space handler script links */
1928         if (slink1->totscript) {
1929                 MEM_freeN(slink1->scripts);
1930                 MEM_freeN(slink1->flag);
1931                 slink1->totscript = 0;
1932         }
1933         if (slink2->totscript) {
1934                 slink1->scripts = MEM_dupallocN(slink2->scripts);
1935                 slink1->flag = MEM_dupallocN(slink2->flag);
1936                 slink1->totscript = slink2->totscript;
1937         }
1938
1939         /* copy pointers */
1940         pa1= sa1->panels.first;
1941         while(pa1) {
1942                 
1943                 patab= sa1->panels.first;
1944                 pa2= sa2->panels.first;
1945                 while(patab) {
1946                         if( pa1->paneltab == pa2) {
1947                                 pa1->paneltab = patab;
1948                                 break;
1949                         }
1950                         patab= patab->next;
1951                         pa2= pa2->next;
1952                 }
1953                 pa1= pa1->next;
1954         }
1955 }
1956
1957 static ScrArea *screen_addarea(bScreen *sc, ScrVert *v1, ScrVert *v2, ScrVert *v3, ScrVert *v4, short headertype, short spacetype)
1958 {
1959         ScrArea *sa= MEM_callocN(sizeof(ScrArea), "addscrarea");
1960         sa->cursor= CURSOR_STD;
1961         sa->v1= v1;
1962         sa->v2= v2;
1963         sa->v3= v3;
1964         sa->v4= v4;
1965         sa->headertype= headertype;
1966         sa->spacetype= spacetype;
1967
1968         calc_arearcts(sa);
1969
1970         if (sa->headertype) openheadwin(sa);
1971         openareawin(sa);
1972
1973         BLI_addtail(&sc->areabase, sa);
1974         return sa;
1975 }
1976
1977 static int rcti_eq(rcti *a, rcti *b) {
1978         return ((a->xmin==b->xmin && a->xmax==b->xmax) &&
1979                         (a->ymin==b->ymin && a->ymax==b->ymax));
1980 }
1981
1982 static void testareas(void)
1983 {
1984         ScrArea *sa, *next;
1985
1986         /* test for header, if removed, or moved */
1987         /* test for window, if removed, or moved */
1988         
1989         for(sa= G.curscreen->areabase.first; sa; sa= next) {
1990                 rcti oldhr= sa->headrct;
1991                 rcti oldwr= sa->winrct;
1992                 
1993                 next= sa->next;
1994                 
1995                 calc_arearcts(sa);
1996                 
1997                 /* ilegally scaled down area.... */
1998                 if(sa->totrct.xmin>=sa->totrct.xmax || sa->totrct.ymin>=sa->totrct.ymax) {
1999                         del_area(sa);
2000                         BLI_remlink(&G.curscreen->areabase, sa);
2001                         MEM_freeN(sa);
2002                         printf("Warning, removed zero sized window from screen %s\n", G.curscreen->id.name+2);
2003                 }
2004                 else {
2005                                 /* test header */
2006                         if (sa->headwin) {
2007                                 if (!rcti_eq(&oldhr, &sa->headrct)) {
2008                                         mywinposition(sa->headwin, sa->headrct.xmin, sa->headrct.xmax, sa->headrct.ymin, sa->headrct.ymax);
2009                                         addqueue(sa->headwin, CHANGED, 1);
2010                                 }
2011                                         
2012                                 if(sa->headbutlen<sa->winx) {
2013                                         sa->headbutofs= 0;
2014                                         addqueue(sa->headwin, CHANGED, 1);
2015                                 }
2016                                 else if(sa->headbutofs+sa->winx > sa->headbutlen) {
2017                                         sa->headbutofs= sa->headbutlen-sa->winx;
2018                                         addqueue(sa->headwin, CHANGED, 1);
2019                                 }
2020                         }
2021
2022                         if (!rcti_eq(&oldwr, &sa->winrct)) {
2023                                 SpaceLink *sl= sa->spacedata.first;
2024                                 
2025                                 mywinposition(sa->win, sa->winrct.xmin, sa->winrct.xmax, sa->winrct.ymin, sa->winrct.ymax);
2026                                 addqueue(sa->win, CHANGED, 1);
2027                                 
2028                                 /* exception handling... probably we need generic event */
2029                                 for(; sl; sl= sl->next)
2030                                         if(sl->spacetype==SPACE_VIEW3D)
2031                                                 BIF_view3d_previewrender_free((View3D *)sl);
2032                         }
2033                 }
2034         }
2035         
2036                 /* remake global windowarray */
2037         memset(areawinar, 0, sizeof(void *)*MAXWIN);
2038         for (sa= G.curscreen->areabase.first; sa; sa= sa->next) {
2039                 areawinar[sa->headwin]= sa;
2040                 areawinar[sa->win]= sa;
2041         }
2042         
2043                 /* test if winakt is OK */      
2044         if( areawinar[G.curscreen->winakt]==0) G.curscreen->winakt= 0;
2045 }
2046
2047 static ScrArea *test_edge_area(ScrArea *sa, ScrEdge *se)
2048 {
2049         /* test if edge is in area, if not, 
2050            then find an area that has it */
2051   
2052         ScrEdge *se1=0, *se2=0, *se3=0, *se4=0;
2053         
2054         if(sa) {
2055                 se1= screen_findedge(G.curscreen, sa->v1, sa->v2);
2056                 se2= screen_findedge(G.curscreen, sa->v2, sa->v3);
2057                 se3= screen_findedge(G.curscreen, sa->v3, sa->v4);
2058                 se4= screen_findedge(G.curscreen, sa->v4, sa->v1);
2059         }
2060         if(se1!=se && se2!=se && se3!=se && se4!=se) {
2061                 
2062                 sa= G.curscreen->areabase.first;
2063                 while(sa) {
2064                         /* a bit optimise? */
2065                         if(se->v1==sa->v1 || se->v1==sa->v2 || se->v1==sa->v3 || se->v1==sa->v4) {
2066                                 se1= screen_findedge(G.curscreen, sa->v1, sa->v2);
2067                                 se2= screen_findedge(G.curscreen, sa->v2, sa->v3);
2068                                 se3= screen_findedge(G.curscreen, sa->v3, sa->v4);
2069                                 se4= screen_findedge(G.curscreen, sa->v4, sa->v1);
2070                                 if(se1==se || se2==se || se3==se || se4==se) return sa;
2071                         }
2072                         sa= sa->next;
2073                 }
2074         }
2075
2076         return sa;      /* is null when not find */
2077 }
2078
2079 ScrArea *closest_bigger_area(void)
2080 {
2081         ScrArea *sa, *big=0;
2082         float cent[3], vec[3],len, len1, len2, len3, dist=1000;
2083         short mval[2];
2084         
2085         getmouseco_sc(mval);
2086         
2087         cent[0]= mval[0];
2088         cent[1]= mval[1];
2089         cent[2]= vec[2]= 0;
2090
2091         sa= G.curscreen->areabase.first;
2092         while(sa) {
2093                 if(sa!=curarea) {
2094                         if(sa->winy>=curarea->winy) {
2095                         
2096                                 /* mimimum of the 4 corners */
2097                                 vec[0]= sa->v1->vec.x; vec[1]= sa->v1->vec.y;
2098                                 len= VecLenf(vec, cent);
2099                                 vec[0]= sa->v2->vec.x; vec[1]= sa->v2->vec.y;
2100                                 len1= VecLenf(vec, cent);
2101                                 vec[0]= sa->v3->vec.x; vec[1]= sa->v3->vec.y;
2102                                 len2= VecLenf(vec, cent);
2103                                 vec[0]= sa->v4->vec.x; vec[1]= sa->v4->vec.y;
2104                                 len3= VecLenf(vec, cent);
2105                                 
2106                                 len= MIN4(len, len1, len2, len3);
2107                                 
2108                                 /* plus center */
2109                                 vec[0]= (sa->v2->vec.x+sa->v3->vec.x)/2;
2110                                 vec[1]= (sa->v1->vec.y+sa->v2->vec.y)/2;
2111
2112                                 len+= 0.5*VecLenf(vec, cent);
2113                                 
2114                                 /* min size */
2115                                 len-= sa->winy+sa->winx;
2116                                 
2117                                 if(len<dist) {
2118                                         dist= len;
2119                                         big= sa;
2120                                 }
2121                         }
2122                 }
2123                 sa= sa->next;
2124         }
2125         
2126         if(big) return big;
2127         else return curarea;
2128 }
2129
2130 /* ************ SCREEN MANAGEMENT ************** */
2131
2132 static int statechanged= 0;
2133 void BIF_wait_for_statechange(void)
2134 {
2135         if (!statechanged) {
2136                         /* Safety, don't wait more than 0.1 seconds */
2137                 double stime= PIL_check_seconds_timer();
2138                 while (!statechanged) {
2139                         winlay_process_events(1);
2140                         if ((PIL_check_seconds_timer()-stime)>0.1) break;
2141                 }
2142                 statechanged= 0;
2143         }
2144         else PIL_sleep_ms(3);   /* statechanged can be set '1' while holding mousebutton, causing locks */
2145
2146 }
2147 void getmouse(short *mval)
2148 {
2149         winlay_process_events(0);
2150         window_get_mouse(mainwin, mval);
2151 }
2152 short get_qual(void)
2153 {
2154         winlay_process_events(0);
2155         return window_get_qual(mainwin);
2156 }
2157 short get_mbut(void)
2158 {
2159         winlay_process_events(0);
2160         return window_get_mbut(mainwin);
2161 }
2162
2163 /* return values of tablet data related functions are documented 
2164  * in the Window struct, ghostwinlay.c */
2165 float get_pressure(void)
2166 {
2167         winlay_process_events(0);
2168         return window_get_pressure(mainwin);
2169 }
2170 void get_tilt(float *xtilt, float *ytilt)
2171 {
2172         winlay_process_events(0);
2173         window_get_tilt(mainwin, xtilt, ytilt);
2174 }
2175 short get_activedevice(void)
2176 {
2177         winlay_process_events(0);
2178         return window_get_activedevice(mainwin);
2179 }
2180
2181 void getndof(float *sbval)
2182 {
2183     winlay_process_events(0);
2184     window_get_ndof(mainwin, sbval);
2185 }
2186
2187 void filterNDOFvalues(float *sbval)
2188 {
2189         int i=0;
2190         float max  = 0.0;
2191         
2192         for (i =0; i<6;i++)
2193                 if (fabs(sbval[i]) > max)
2194                         max = fabs(sbval[i]);
2195         for (i =0; i<6;i++)
2196                 if (fabs(sbval[i]) != max )
2197                         sbval[i]=0.0;
2198 }
2199
2200 void add_to_mainqueue(Window *win, void *user_data, short evt, short val, char ascii)
2201 {
2202
2203         statechanged= 1;
2204
2205         /*  accept the extended ascii set (ton) */
2206         if( !val || ascii<32 ) {
2207                 ascii= '\0';
2208         }
2209
2210         mainqenter_ext(evt, val, ascii);
2211 }
2212
2213 /* ScrVert ordering in a ScrArea:
2214
2215 2---------3
2216 |         |
2217 |         |
2218 1---------4
2219   
2220 */
2221
2222 static bScreen *addscreen(char *name)           /* use setprefsize() if you want something else than a full windpw */
2223 {
2224         /* this function sets variabele G.curscreen,
2225          * that global is about used everywhere!
2226          */
2227         bScreen *sc;
2228         ScrVert *sv1, *sv2, *sv3, *sv4;
2229         short startx, starty, endx, endy;       
2230         
2231         sc= G.curscreen= alloc_libblock(&G.main->screen, ID_SCR, name);
2232
2233         if (!prefsizx) {
2234                 prefstax= 0;
2235                 prefstay= 0;
2236                 
2237                 winlay_get_screensize(&prefsizx, &prefsizy);
2238         }
2239
2240         startx= prefstax;
2241         starty= prefstay;
2242         endx= prefstax+prefsizx-1;
2243         endy= prefstay+prefsizy-1;
2244
2245         sc->startx= startx;     sc->starty= starty;
2246         sc->endx= endx; sc->endy= endy;
2247         sc->sizex= sc->endx-sc->startx+1;
2248         sc->sizey= sc->endy-sc->starty+1;
2249         
2250         sc->scene= G.scene;
2251         
2252         if (!mainwin) {
2253                 if (G.windowstate == G_WINDOWSTATE_FULLSCREEN)
2254                         mainwin= window_open("Blender", sc->startx, sc->starty, sc->sizex, sc->sizey, G_WINDOWSTATE_FULLSCREEN);
2255                 else
2256                         mainwin= window_open("Blender", sc->startx, sc->starty, sc->sizex, sc->sizey, start_maximized);
2257                 
2258                 if (!mainwin) {
2259                         printf("ERROR: Unable to open Blender window\n");
2260                         exit(1);
2261                 }
2262                 
2263                 window_set_handler(mainwin, add_to_mainqueue, NULL);
2264                 window_open_ndof(mainwin); /* needs to occur once the mainwin handler is set */
2265                 init_mainwin();
2266                 mywinset(1);
2267         
2268                 /* for visual speed, but still needed? */
2269                 glClearColor(.55, .55, .55, 0.0);
2270                 glClear(GL_COLOR_BUFFER_BIT);
2271                 window_swap_buffers(mainwin);
2272                 
2273                 /* this is unneeded and with large monitors can be a
2274                  * pain so commenting out */
2275                 /* warp_pointer(sc->sizex/2,  sc->sizey/2); */
2276                 
2277                 mainqenter(REDRAW, 1);
2278         }
2279
2280         sc->mainwin= 1;
2281         
2282         sv1= screen_addvert(sc, 0, 0);
2283         sv2= screen_addvert(sc, 0, sc->endy-sc->starty);
2284         sv3= screen_addvert(sc, sc->sizex-1, sc->sizey-1);
2285         sv4= screen_addvert(sc, sc->sizex-1, 0);
2286         
2287         screen_addedge(sc, sv1, sv2);
2288         screen_addedge(sc, sv2, sv3);
2289         screen_addedge(sc, sv3, sv4);
2290         screen_addedge(sc, sv4, sv1);
2291
2292         screen_addarea(sc, sv1, sv2, sv3, sv4, HEADERDOWN, SPACE_INFO);
2293         
2294         G.curscreen= sc;
2295
2296         return sc;
2297 }
2298
2299 void setscreen(bScreen *sc)
2300 {
2301         bScreen *sc1;
2302         ScrArea *sa;
2303         short mval[2];
2304         
2305         if(sc->full) {                          /* find associated full */
2306                 sc1= G.main->screen.first;
2307                 while(sc1) {
2308                         sa= sc1->areabase.first;
2309                         if(sa->full==sc) {
2310                                 sc= sc1;
2311                                 break;
2312                         }
2313                         sc1= sc1->id.next;
2314                 }
2315                 if(sc1==0) printf("setscreen error\n");
2316         }
2317
2318         /* de-activate G.curscreen */
2319         if (G.curscreen && G.curscreen != sc) {
2320                 sa= G.curscreen->areabase.first;
2321                 while(sa) {
2322                         if(sa->win) mywinclose(sa->win);
2323                         sa->win= 0;
2324                         if(sa->headwin) mywinclose(sa->headwin);
2325                         sa->headwin= 0;
2326                         
2327                         uiFreeBlocks(&sa->uiblocks);
2328                         
2329                         sa= sa->next;
2330                 }               
2331         }
2332         else if(G.curscreen) markdirty_all();   /* at least redraw */
2333
2334         if (G.curscreen != sc) {
2335                 mywinset(sc->mainwin);
2336         }
2337         
2338         G.curscreen= sc;
2339
2340         for (sa= sc->areabase.first; sa; sa= sa->next) {
2341                         /* XXX, fixme zr */
2342 /*              if (sa->win || sa->headwin) */
2343 /*                      printf("error in setscreen (win): %d, %d\n", sa->win, sa->headwin); */
2344                 if (!sa->win)
2345                         openareawin(sa);
2346                 if (!sa->headwin && sa->headertype)
2347                         openheadwin(sa);
2348         }
2349
2350         /* recalculate winakt */
2351         getmouseco_sc(mval);
2352
2353         test_scale_screen(sc);
2354         testareas();
2355         
2356         for(sa= sc->areabase.first; sa; sa= sa->next) {
2357                 SpaceLink *sl;
2358                 
2359                 for(sl= sa->spacedata.first; sl; sl= sl->next) {
2360                         sl->area= sa;
2361
2362                         if(sl->spacetype==SPACE_OOPS) {
2363                                 SpaceOops *soops= (SpaceOops *) sl;
2364
2365                                 /* patch for old files */
2366                                 if(soops->v2d.cur.xmin==soops->v2d.cur.xmax) {
2367                                         init_v2d_oops(sa, soops);
2368                                 }
2369                         }
2370                         else if(sl->spacetype==SPACE_BUTS) {
2371                                 SpaceButs *sbuts= (SpaceButs *)sl;
2372                                 sbuts->re_align= 1;             // force an align call, maybe new panels were added, also for after file reading
2373                         }
2374                 }
2375                 
2376                 sa->cursor= CURSOR_STD;
2377         }
2378         
2379         if(G.scene!=sc->scene)
2380                 set_scene(sc->scene);
2381
2382         countall();
2383         
2384         G.curscreen->winakt= 0;
2385         curarea= sc->areabase.first;
2386         
2387         mainqenter(DRAWEDGES, 1);
2388         dodrawscreen= 1;                /* patch! even gets lost,,,? */
2389
2390         winqueue_break= 1;              /* means leave queue everywhere */
2391 }
2392
2393 static void splitarea(ScrArea *sa, char dir, float fac);
2394
2395 void area_fullscreen(void)      /* with curarea */
2396 {
2397         /* this function toggles: if area is full then the parent will be restored */
2398         bScreen *sc, *oldscreen;
2399         ScrArea *sa, *newa, *old;
2400         short headertype, fulltype;
2401         
2402         if(curarea->full) {
2403                 sc= curarea->full;      /* the old screen */
2404                 fulltype = sc->full;
2405
2406                 // refuse to go out of SCREENAUTOPLAY as long as G_FLAGS_AUTOPLAY
2407                 // is set
2408
2409                 if (fulltype != SCREENAUTOPLAY || (G.flags & G_FILE_AUTOPLAY) == 0) {
2410                         sc->full= 0;
2411                 
2412                         /* find old area */
2413                         old= sc->areabase.first;
2414                         while(old) {
2415                                 if(old->full) break;
2416                                 old= old->next;
2417                         }
2418                         if(old==0) {error("something wrong in areafullscreen"); return;}
2419                 
2420                         if (fulltype == SCREENAUTOPLAY) {
2421                                 // in autoplay screens the headers are disabled by 
2422                                 // default. So use the old headertype instead
2423                                 headertype = old->headertype;
2424                         } else {
2425                                 // normal fullscreen. Use current headertype
2426                                 headertype = curarea->headertype;
2427                         }
2428
2429                         copy_areadata(old, curarea, 1); /*  1 = swap spacelist */
2430                         old->headertype = headertype;
2431
2432                         old->full= 0;
2433                 
2434                         unlink_screen(G.curscreen);
2435                         free_libblock(&G.main->screen, G.curscreen);
2436                         G.curscreen= NULL;
2437
2438                         setscreen(sc);
2439                 }
2440                 
2441         }
2442         else {
2443                 /* is there only 1 area? */
2444                 if(G.curscreen->areabase.first==G.curscreen->areabase.last) return;
2445                 if(curarea->spacetype==SPACE_INFO) return;
2446                 
2447                 G.curscreen->full = SCREENFULL;
2448                 
2449                 old= curarea;           
2450                 oldscreen= G.curscreen;
2451                 sc= addscreen("temp");          /* this sets G.curscreen */
2452
2453                 splitarea( (ScrArea *)sc->areabase.first, 'h', 0.99);
2454                 newa= sc->areabase.first;
2455                 newspace(newa->next, SPACE_INFO);
2456                 
2457                 curarea= old;
2458                 G.curscreen= oldscreen; /* needed because of setscreen */
2459                 
2460                 /* copy area */
2461                 copy_areadata(newa, curarea, 1);        /* 1 = swap spacelist */
2462                 
2463                 curarea->full= oldscreen;
2464                 newa->full= oldscreen;
2465                 newa->next->full= oldscreen;
2466                 
2467                 setscreen(sc);
2468                 wich_cursor(newa);
2469         }
2470         
2471         /* there's also events in queue for this, but we call fullscreen for render output
2472         now, and that doesn't go back to queue. Bad code, but doesn't hurt... (ton) */
2473         for(sa= G.curscreen->areabase.first; sa; sa= sa->next) {
2474                 scrarea_do_headchange(sa);
2475                 scrarea_do_winchange(sa);
2476         }
2477         /* bad code #2: setscreen() ends with first area active. fullscreen render assumes this too */
2478         curarea= sc->areabase.first;
2479         
2480         retopo_force_update();
2481 }
2482
2483 static void area_autoplayscreen(void)
2484 {
2485         bScreen *sc, *oldscreen;
2486         ScrArea *newa, *old, *sa;
2487         
2488         if (curarea->full) {
2489                 area_fullscreen();
2490         }
2491
2492         if (curarea->full == NULL) { 
2493                 sa = G.curscreen->areabase.first;
2494                 while (sa) {
2495                         if (sa->spacetype == SPACE_VIEW3D) {
2496                                 break;
2497                         }
2498                         sa= sa->next;
2499                 }
2500
2501                 if (sa) {
2502                         areawinset(sa->win);
2503                         G.curscreen->full = SCREENAUTOPLAY;
2504                         
2505                         old= curarea;           
2506                         oldscreen= G.curscreen;
2507                         sc= addscreen("temp");          /* this sets G.curscreen */
2508         
2509                         newa= sc->areabase.first;
2510                         
2511                         curarea= old;
2512                         G.curscreen= oldscreen; /* because of setscreen */
2513                         
2514                         /* copy area settings */
2515                         copy_areadata(newa, curarea, 1);        /* swap spacedata */
2516                         newa->headertype= 0;
2517                         
2518                         curarea->full= oldscreen;
2519                         newa->full= oldscreen;
2520         
2521                         setscreen(sc);
2522                         wich_cursor(newa);
2523                 }
2524         }
2525 }
2526
2527 static void copy_screen(bScreen *to, bScreen *from)
2528 {
2529         ScrVert *s1, *s2;
2530         ScrEdge *se;
2531         ScrArea *sa, *saf;
2532
2533         /* free 'to' */
2534         free_screen(to);
2535         winqueue_break= 1;      /* leave queues everywhere */
2536         
2537         duplicatelist(&to->vertbase, &from->vertbase);
2538         duplicatelist(&to->edgebase, &from->edgebase);
2539         duplicatelist(&to->areabase, &from->areabase);
2540         
2541         s1= from->vertbase.first;
2542         s2= to->vertbase.first;
2543         while(s1) {
2544                 s1->newv= s2;
2545                 s2= s2->next;
2546                 s1= s1->next;
2547         }
2548         se= to->edgebase.first;
2549         while(se) {
2550                 se->v1= se->v1->newv;
2551                 se->v2= se->v2->newv;
2552                 sortscrvert(&(se->v1), &(se->v2));
2553                 se= se->next;
2554         }
2555
2556         sa= to->areabase.first;
2557         saf= from->areabase.first;
2558         while(sa) {
2559                 sa->v1= sa->v1->newv;
2560                 sa->v2= sa->v2->newv;
2561                 sa->v3= sa->v3->newv;
2562                 sa->v4= sa->v4->newv;
2563                 sa->win= 0;
2564                 sa->headwin= 0;
2565                 
2566                 sa->spacedata.first= sa->spacedata.last= NULL;
2567                 sa->uiblocks.first= sa->uiblocks.last= NULL;
2568                 sa->panels.first= sa->panels.last= NULL;
2569                 sa->scriptlink.totscript= 0;
2570                 
2571                 copy_areadata(sa, saf, 0);
2572                 
2573                 sa= sa->next;
2574                 saf= saf->next;
2575         }
2576         
2577         /* put at zero (needed?) */
2578         s1= from->vertbase.first;
2579         while(s1) {
2580                 s1->newv= 0;
2581                 s1= s1->next;
2582         }
2583 }
2584
2585 void duplicate_screen(void)
2586 {
2587         bScreen *sc, *oldscreen;
2588         
2589         if(G.curscreen->full != SCREENNORMAL) return;
2590         
2591         /* make new screen: */
2592
2593         oldscreen= G.curscreen;
2594         sc= addscreen(oldscreen->id.name+2);    /* this sets G.curscreen */
2595         copy_screen(sc, oldscreen);
2596
2597         G.curscreen= oldscreen;
2598         setscreen(sc);
2599
2600 }
2601
2602
2603 /* ************ END SCREEN MANAGEMENT ************** */
2604 /* ************  JOIN/SPLIT/MOVE ************** */
2605
2606 typedef struct point{
2607         float x,y;
2608 }_point;
2609
2610 /* draw vertical shape visualising future joining (left as well
2611  * right direction of future joining) */
2612 static void draw_horizontal_join_shape(ScrArea *sa, char dir)
2613 {
2614         _point points[10];
2615         short i;
2616         float w, h;
2617         float width = sa->v3->vec.x - sa->v1->vec.x;
2618         float height = sa->v3->vec.y - sa->v1->vec.y;
2619
2620         if(height<width) {
2621                 h = height/8;
2622                 w = height/4;
2623         }
2624         else {
2625                 h = width/8;
2626                 w = width/4;
2627         }
2628
2629         points[0].x = sa->v1->vec.x;
2630         points[0].y = sa->v1->vec.y + height/2;
2631
2632         points[1].x = sa->v1->vec.x;
2633         points[1].y = sa->v1->vec.y;
2634
2635         points[2].x = sa->v4->vec.x - w;
2636         points[2].y = sa->v4->vec.y;
2637
2638         points[3].x = sa->v4->vec.x - w;
2639         points[3].y = sa->v4->vec.y + height/2 - 2*h;
2640
2641         points[4].x = sa->v4->vec.x - 2*w;
2642         points[4].y = sa->v4->vec.y + height/2;
2643
2644         points[5].x = sa->v4->vec.x - w;
2645         points[5].y = sa->v4->vec.y + height/2 + 2*h;
2646
2647         points[6].x = sa->v3->vec.x - w;
2648         points[6].y = sa->v3->vec.y;
2649
2650         points[7].x = sa->v2->vec.x;
2651         points[7].y = sa->v2->vec.y;
2652
2653         points[8].x = sa->v4->vec.x;
2654         points[8].y = sa->v4->vec.y + height/2 - h;
2655
2656         points[9].x = sa->v4->vec.x;
2657         points[9].y = sa->v4->vec.y + height/2 + h;
2658
2659         if(dir=='l') {
2660                 /* when direction is left, then we flip direction of arrow */
2661                 float cx = sa->v1->vec.x + width;
2662                 for(i=0;i<10;i++) {
2663                         points[i].x -= cx;
2664                         points[i].x = -points[i].x;
2665                         points[i].x += sa->v1->vec.x;
2666                 }
2667         }
2668
2669         glBegin(GL_POLYGON);
2670         for(i=0;i<5;i++)
2671                 glVertex2f(points[i].x, points[i].y);
2672         glEnd();
2673         glBegin(GL_POLYGON);
2674         for(i=4;i<8;i++)
2675                 glVertex2f(points[i].x, points[i].y);
2676         glVertex2f(points[0].x, points[0].y);
2677         glEnd();
2678
2679         glRectf(points[2].x, points[2].y, points[8].x, points[8].y);
2680         glRectf(points[6].x, points[6].y, points[9].x, points[9].y);
2681 }
2682
2683 /* draw vertical shape visualising future joining (up/down direction) */
2684 static void draw_vertical_join_shape(ScrArea *sa, char dir)
2685 {
2686         _point points[10];
2687         short i;
2688         float w, h;
2689         float width = sa->v3->vec.x - sa->v1->vec.x;
2690         float height = sa->v3->vec.y - sa->v1->vec.y;
2691
2692         if(height<width) {
2693                 h = height/4;
2694                 w = height/8;
2695         }
2696         else {
2697                 h = width/4;
2698                 w = width/8;
2699         }
2700
2701         points[0].x = sa->v1->vec.x + width/2;
2702         points[0].y = sa->v3->vec.y;
2703
2704         points[1].x = sa->v2->vec.x;
2705         points[1].y = sa->v2->vec.y;
2706
2707         points[2].x = sa->v1->vec.x;
2708         points[2].y = sa->v1->vec.y + h;
2709
2710         points[3].x = sa->v1->vec.x + width/2 - 2*w;
2711         points[3].y = sa->v1->vec.y + h;
2712
2713         points[4].x = sa->v1->vec.x + width/2;
2714         points[4].y = sa->v1->vec.y + 2*h;
2715
2716         points[5].x = sa->v1->vec.x + width/2 + 2*w;
2717         points[5].y = sa->v1->vec.y + h;
2718
2719         points[6].x = sa->v4->vec.x;
2720         points[6].y = sa->v4->vec.y + h;
2721         
2722         points[7].x = sa->v3->vec.x;
2723         points[7].y = sa->v3->vec.y;
2724
2725         points[8].x = sa->v1->vec.x + width/2 - w;
2726         points[8].y = sa->v1->vec.y;
2727
2728         points[9].x = sa->v1->vec.x + width/2 + w;
2729         points[9].y = sa->v1->vec.y;
2730
2731         if(dir=='u') {
2732                 /* when direction is up, then we flip direction of arrow */
2733                 float cy = sa->v1->vec.y + height;
2734                 for(i=0;i<10;i++) {
2735                         points[i].y -= cy;
2736                         points[i].y = -points[i].y;
2737                         points[i].y += sa->v1->vec.y;
2738                 }
2739         }
2740
2741         glBegin(GL_POLYGON);
2742         for(i=0;i<5;i++)
2743                 glVertex2f(points[i].x, points[i].y);
2744         glEnd();
2745         glBegin(GL_POLYGON);
2746         for(i=4;i<8;i++)
2747                 glVertex2f(points[i].x, points[i].y);
2748         glVertex2f(points[0].x, points[0].y);
2749         glEnd();
2750
2751         glRectf(points[2].x, points[2].y, points[8].x, points[8].y);
2752         glRectf(points[6].x, points[6].y, points[9].x, points[9].y);
2753 }
2754
2755 /* draw join shape due to direction of joining */
2756 static void draw_join_shape(ScrArea *sa, char dir)
2757 {
2758         if(dir=='u' || dir=='d')
2759                 draw_vertical_join_shape(sa, dir);
2760         else
2761                 draw_horizontal_join_shape(sa, dir);
2762 }
2763
2764 /* draw screen area darker with arrow (visualisation of future joining) */
2765 static void scrarea_draw_shape_dark(ScrArea *sa, char dir)
2766 {
2767         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
2768         glEnable(GL_BLEND);
2769         glColor4ub(0, 0, 0, 105);
2770         draw_join_shape(sa, dir);
2771         glDisable(GL_BLEND);
2772 }
2773
2774 /* draw screen area ligher with arrow shape ("eraser" of previous dark shape) */
2775 static void scrarea_draw_shape_light(ScrArea *sa, char dir)
2776 {
2777         glBlendFunc(GL_DST_COLOR, GL_SRC_ALPHA);
2778         glEnable(GL_BLEND);
2779         /* value 181 was hardly computed: 181~105 */
2780         glColor4ub(255, 255, 255, 181);         
2781         draw_join_shape(sa, dir);
2782         glDisable(GL_BLEND);
2783 }
2784
2785 static void joinarea_interactive(ScrArea *area, ScrEdge *onedge)
2786 {
2787         struct ScrArea *sa1 = area, *sa2, *scr;
2788         struct ScrArea *up=0, *down=0, *right=0, *left=0;
2789         struct ScrEdge *se;
2790         unsigned short event;
2791         short ok=0, val=0, mval[2];
2792         char dir=0;
2793
2794         sa1 = test_edge_area(sa1, onedge);
2795         if(sa1==0) return;
2796
2797         /* find directions with same edge */
2798         sa2= G.curscreen->areabase.first;
2799         while(sa2) {
2800                 if(sa2 != sa1) {
2801                         se= screen_findedge(G.curscreen, sa2->v1, sa2->v2);
2802                         if(onedge==se) right= sa2;
2803                         se= screen_findedge(G.curscreen, sa2->v2, sa2->v3);
2804                         if(onedge==se) down= sa2;
2805                         se= screen_findedge(G.curscreen, sa2->v3, sa2->v4);
2806                         if(onedge==se) left= sa2;
2807                         se= screen_findedge(G.curscreen, sa2->v4, sa2->v1);
2808                         if(onedge==se) up= sa2;
2809                 }
2810                 sa2= sa2->next;
2811         }
2812         
2813         if(left) val++;
2814         if(up) val++;
2815         if(right) val++;
2816         if(down) val++;
2817         
2818         if(val==0) return;
2819         else if(val==1) {
2820                 if(left) {
2821                         right = sa1;
2822                         sa2 = left;
2823                         dir = 'h';
2824                 }
2825                 else if(right) {
2826                         left = sa1;
2827                         sa2 = right;
2828                         dir = 'h';
2829                 }
2830                 else if(up) {
2831                         down = sa1;
2832                         sa2= up;
2833                         dir = 'v';
2834                 }
2835                 else if(down) {
2836                         up = sa1;
2837                         sa2 = down;
2838                         dir = 'v';
2839                 }
2840         }
2841
2842         mywinset(G.curscreen->mainwin);
2843
2844         /* initial set up screen area asigned for destroying */
2845         scr = sa2;
2846
2847         /* set up standard cursor */
2848         set_cursor(CURSOR_STD);
2849
2850         /* should already have a good matrix */
2851         glReadBuffer(GL_FRONT);
2852         glDrawBuffer(GL_FRONT);
2853
2854         /* to prevent flickering after clicking at "Join Areas " */
2855         getmouseco_sc(mval);
2856         if(dir=='h') {
2857                 if(scr==left && mval[0]>=onedge->v1->vec.x) scr = right;
2858                 else if(scr==right && mval[0]<onedge->v1->vec.x) scr = left;
2859         }
2860         else if(dir=='v') {
2861                 if(scr==down && mval[1]>=onedge->v1->vec.y) scr = up;
2862                 else if(scr==up && mval[1]<onedge->v1->vec.y) scr = down;
2863         }
2864
2865         /* draw scr screen area with dark shape */
2866         if(scr==left)
2867                 scrarea_draw_shape_dark(scr,'r');
2868         else if(scr==right)
2869                 scrarea_draw_shape_dark(scr,'l');
2870         else if(scr==up)
2871                 scrarea_draw_shape_dark(scr,'d');
2872         else if(scr==down)
2873                 scrarea_draw_shape_dark(scr,'u');
2874         bglFlush();
2875
2876         /* "never ending loop" of interactive selection */
2877         while(!ok) {
2878                 getmouseco_sc(mval);
2879
2880                 /* test if position of mouse is on the "different side" of
2881                  * "joining edge" */
2882                 if(dir=='h') {
2883                         if(scr==left && mval[0]>=onedge->v1->vec.x) {
2884                                 scrarea_draw_shape_light(scr,'r');
2885                                 scr = right;
2886                                 scrarea_draw_shape_dark(scr,'l');
2887                         }
2888                         else if(scr==right && mval[0]<onedge->v1->vec.x) {
2889                                 scrarea_draw_shape_light(scr,'l');
2890                                 scr = left;
2891                                 scrarea_draw_shape_dark(scr,'r');
2892                         }
2893                 }
2894                 else if(dir=='v') {
2895                         if(scr==down && mval[1]>=onedge->v1->vec.y) {
2896                                 scrarea_draw_shape_light(scr,'u');
2897                                 scr = up;
2898                                 scrarea_draw_shape_dark(scr,'d');
2899                         }
2900                         else if(scr==up && mval[1]<onedge->v1->vec.y){
2901                                 scrarea_draw_shape_light(scr,'d');
2902                                 scr = down;
2903                                 scrarea_draw_shape_dark(scr,'u');
2904                         }
2905                 }
2906
2907
2908                 /* get pressed keys and mouse buttons */
2909                 event = extern_qread(&val);
2910
2911                 /* confirm joining of two screen areas */
2912                 if(val && event==LEFTMOUSE) ok= 1;
2913
2914                 /* cancel joining of joining */
2915                 if(val && (event==ESCKEY || event==RIGHTMOUSE)) ok= -1;
2916
2917                 bglFlush();
2918         }
2919
2920         glReadBuffer(GL_BACK);
2921         glDrawBuffer(GL_BACK);
2922
2923         /* joining af screen areas was confirmed ... proceed joining */
2924         if(ok==1) {
2925                 if(sa2!=scr) {
2926                         sa1 = sa2;
2927                         sa2 = scr;
2928                 }
2929
2930                 if(sa2==left) {
2931                         sa1->v1= sa2->v1;
2932                         sa1->v2= sa2->v2;
2933                         screen_addedge(G.curscreen, sa1->v2, sa1->v3);
2934                         screen_addedge(G.curscreen, sa1->v1, sa1->v4);
2935                 }
2936                 else if(sa2==up) {
2937                         sa1->v2= sa2->v2;
2938                         sa1->v3= sa2->v3;
2939                         screen_addedge(G.curscreen, sa1->v1, sa1->v2);
2940                         screen_addedge(G.curscreen, sa1->v3, sa1->v4);
2941                 }
2942                 else if(sa2==right) {
2943                         sa1->v3= sa2->v3;
2944                         sa1->v4= sa2->v4;
2945                         screen_addedge(G.curscreen, sa1->v2, sa1->v3);
2946                         screen_addedge(G.curscreen, sa1->v1, sa1->v4);
2947                 }
2948                 else if(sa2==down) {
2949                         sa1->v1= sa2->v1;
2950                         sa1->v4= sa2->v4;
2951                         screen_addedge(G.curscreen, sa1->v1, sa1->v2);
2952                         screen_addedge(G.curscreen, sa1->v3, sa1->v4);
2953                 }
2954         
2955                 del_area(sa2);
2956                 BLI_remlink(&G.curscreen->areabase, sa2);
2957                 MEM_freeN(sa2);
2958                 
2959                 removedouble_scredges();
2960                 removenotused_scredges();
2961                 removenotused_scrverts();
2962                 
2963                 testareas();
2964                 mainqenter(DRAWEDGES, 1);
2965
2966                 /* test cursor en inputwindow */
2967                 mainqenter(MOUSEY, -1);
2968         }
2969 }
2970
2971 static short testsplitpoint(ScrArea *sa, char dir, float fac)
2972 /* return 0: no split possible */
2973 /* else return (integer) screencoordinate split point */
2974 {
2975         short x, y;
2976         
2977         /* area big enough? */
2978         if(sa->v4->vec.x- sa->v1->vec.x <= 2*AREAMINX) return 0;
2979         if(sa->v2->vec.y- sa->v1->vec.y <= 2*AREAMINY) return 0;
2980
2981         /* to be sure */
2982         if(fac<0.0) fac= 0.0;
2983         if(fac>1.0) fac= 1.0;
2984         
2985         if(dir=='h') {
2986                 y= sa->v1->vec.y+ fac*(sa->v2->vec.y- sa->v1->vec.y);
2987                 
2988                 if(sa->v2->vec.y==G.curscreen->sizey-1 && sa->v2->vec.y- y < HEADERY) 
2989                         y= sa->v2->vec.y- HEADERY;
2990
2991                 else if(sa->v1->vec.y==0 && y- sa->v1->vec.y < HEADERY)
2992                         y= sa->v1->vec.y+ HEADERY;
2993
2994                 else if(y- sa->v1->vec.y < AREAMINY) y= sa->v1->vec.y+ AREAMINY;
2995                 else if(sa->v2->vec.y- y < AREAMINY) y= sa->v2->vec.y- AREAMINY;
2996                 else y-= (y % AREAGRID);
2997
2998                 return y;
2999         }
3000         else {
3001                 x= sa->v1->vec.x+ fac*(sa->v4->vec.x- sa->v1->vec.x);
3002                 if(x- sa->v1->vec.x < AREAMINX) x= sa->v1->vec.x+ AREAMINX;
3003                 else if(sa->v4->vec.x- x < AREAMINX) x= sa->v4->vec.x- AREAMINX;
3004                 else x-= (x % AREAGRID);
3005
3006                 return x;
3007         }
3008 }
3009
3010 static void splitarea(ScrArea *sa, char dir, float fac)
3011 {
3012         bScreen *sc;
3013         ScrArea *newa=NULL;
3014         ScrVert *sv1, *sv2;
3015         short split;
3016         
3017         if(sa==0) return;
3018         
3019         split= testsplitpoint(sa, dir, fac);
3020         if(split==0) return;
3021         
3022         sc= G.curscreen;
3023         
3024         areawinset(sa->win);
3025         
3026         if(dir=='h') {
3027                 /* new vertices */
3028                 sv1= screen_addvert(sc, sa->v1->vec.x, split);
3029                 sv2= screen_addvert(sc, sa->v4->vec.x, split);
3030                 
3031                 /* new edges */
3032                 screen_addedge(sc, sa->v1, sv1);
3033                 screen_addedge(sc, sv1, sa->v2);
3034                 screen_addedge(sc, sa->v3, sv2);
3035                 screen_addedge(sc, sv2, sa->v4);
3036                 screen_addedge(sc, sv1, sv2);
3037                 
3038                 /* new areas: top */
3039                 newa= screen_addarea(sc, sv1, sa->v2, sa->v3, sv2, sa->headertype, sa->spacetype);
3040                 copy_areadata(newa, sa, 0);
3041
3042                 /* area below */
3043                 sa->v2= sv1;
3044                 sa->v3= sv2;
3045                 
3046         }
3047         else {
3048                 /* new vertices */
3049                 sv1= screen_addvert(sc, split, sa->v1->vec.y);
3050                 sv2= screen_addvert(sc, split, sa->v2->vec.y);
3051                 
3052                 /* new edges */
3053                 screen_addedge(sc, sa->v1, sv1);
3054                 screen_addedge(sc, sv1, sa->v4);
3055                 screen_addedge(sc, sa->v2, sv2);
3056                 screen_addedge(sc, sv2, sa->v3);
3057                 screen_addedge(sc, sv1, sv2);
3058                 
3059                 /* new areas: left */
3060                 newa= screen_addarea(sc, sa->v1, sa->v2, sv2, sv1, sa->headertype, sa->spacetype);
3061                 copy_areadata(newa, sa, 0);
3062
3063                 /* area right */
3064                 sa->v1= sv1;            
3065                 sa->v2= sv2;
3066         }
3067         
3068         if(sa->spacetype==SPACE_BUTS) {
3069                 addqueue(sa->win, UI_BUT_EVENT, B_BUTSHOME);
3070                 addqueue(newa->win, UI_BUT_EVENT, B_BUTSHOME);
3071         }
3072         
3073         /* remove double vertices en edges */
3074         removedouble_scrverts();
3075         removedouble_scredges();
3076         removenotused_scredges();
3077         
3078         mainqenter(DRAWEDGES, 1);
3079         dodrawscreen= 1;                /* patch! event gets lost,,,? */
3080         testareas();
3081 }
3082
3083 static void scrarea_draw_splitpoint(ScrArea *sa, char dir, float fac)
3084 {
3085         int split= testsplitpoint(sa, dir, fac);
3086
3087         if (split) {
3088                 if(dir=='h') {
3089                         sdrawXORline(sa->totrct.xmin, split, sa->totrct.xmax, split);
3090                         sdrawXORline(sa->totrct.xmin, split-1, sa->totrct.xmax, split-1);
3091                 } else {
3092                         sdrawXORline(split, sa->totrct.ymin, split, sa->totrct.ymax);
3093                         sdrawXORline(split-1, sa->totrct.ymin, split-1, sa->totrct.ymax);
3094                 }
3095         }
3096 }
3097
3098 static void splitarea_interactive(ScrArea *area, ScrEdge *onedge)
3099 {
3100         ScrArea *scr, *sa= area;
3101         float fac= 0.0;
3102         unsigned short event;
3103         short ok= 0, val, split = 0, mval[2], mvalo[2]= {-1, -1}, first= 1;
3104         char dir;
3105         
3106         if(sa->win==0) return;
3107         if(sa->full) return;
3108         if(myswinopen_allowed()==0) {
3109                 error("Max amount of subwindows reached");
3110                 return;
3111         }
3112         
3113         dir= scredge_is_horizontal(onedge)?'v':'h';
3114         
3115         mywinset(G.curscreen->mainwin);
3116         /* should already have a good matrix */
3117         glReadBuffer(GL_FRONT);
3118         glDrawBuffer(GL_FRONT);
3119
3120         /* keep track of grid and minsize */
3121         while(ok==0) {
3122                 getmouseco_sc(mval);
3123
3124                 /* this part of code allows to choose, what window will be splited */
3125                 /* cursor is out of the current ScreenArea */
3126                 if((mval[0] < sa->v1->vec.x) || (mval[0] > sa->v3->vec.x) ||
3127                 (mval[1] < sa->v1->vec.y) || (mval[1] > sa->v3->vec.y)){
3128                         scr= (ScrArea*)G.curscreen->areabase.first;
3129                         while(scr){
3130                                 if((mval[0] > scr->v1->vec.x) && (mval[0] < scr->v4->vec.x) &&
3131                                 (mval[1] < scr->v2->vec.y) && (mval[1] > scr->v1->vec.y)){
3132                                         /* test: is ScreenArea enough big for splitting */
3133                                         short tsplit= testsplitpoint(scr, dir, fac);
3134                                         if(tsplit){
3135                                                 split = tsplit;
3136                                                 /* delete old line from previous ScreenArea */
3137                                                 if(!first) scrarea_draw_splitpoint(sa, dir, fac);
3138                                                 sa= scr;
3139                                                 first= 1;
3140                                                 break;
3141                                         }
3142                                 }
3143                                 scr= scr->next;
3144                         }
3145                 }
3146                 
3147                 if (first || (dir=='v' && mval[0]!=mvalo[0]) || (dir=='h' && mval[1]!=mvalo[1])) {
3148                         if (!first) {
3149                                 scrarea_draw_splitpoint(sa, dir, fac);
3150                         }
3151
3152                         if(dir=='h') {
3153                                 fac= mval[1]- (sa->v1->vec.y);
3154                                 fac/= sa->v2->vec.y- sa->v1->vec.y;
3155                         } else {
3156                                 fac= mval[0]- sa->v1->vec.x;
3157                                 fac/= sa->v4->vec.x- sa->v1->vec.x;
3158                         }
3159
3160                         split= testsplitpoint(sa, dir, fac);
3161                         if (split) {
3162                                 scrarea_draw_splitpoint(sa, dir, fac);
3163                         } else {
3164                                 ok= -1;
3165                         }
3166
3167                         mvalo[0]= mval[0];
3168                         mvalo[1]= mval[1];
3169                         first= 0;                       
3170                 }
3171                 
3172                 event= extern_qread(&val);
3173
3174                 /* change direction of splitting between horizontal and vertical
3175                  * patch was offered by Guillaume */
3176                 if(val && (event==TABKEY || event==MIDDLEMOUSE)) {
3177                         scrarea_draw_splitpoint(sa, dir, fac);
3178                         if(dir=='h') {
3179                                 dir='v';
3180                                 set_cursor(CURSOR_Y_MOVE);
3181                         } else {
3182                                 dir='h';
3183                                 set_cursor(CURSOR_X_MOVE);
3184                         }
3185                         first= 1;
3186                 }
3187
3188                 if(val && event==LEFTMOUSE) {
3189                         if(dir=='h') {
3190                                 fac= split- (sa->v1->vec.y);
3191                                 fac/= sa->v2->vec.y- sa->v1->vec.y;
3192                         }
3193                         else {
3194                                 fac= split- sa->v1->vec.x;
3195                                 fac/= sa->v4->vec.x- sa->v1->vec.x;
3196                         }
3197                         ok= 1;
3198                 }
3199                 if(val && (event==ESCKEY || event==RIGHTMOUSE)) {
3200                         ok= -1;
3201                 }
3202                 bglFlush();
3203         }
3204
3205         if (!first) {
3206                 scrarea_draw_splitpoint(sa, dir, fac);
3207                 bglFlush();
3208         }
3209         glReadBuffer(GL_BACK);
3210         glDrawBuffer(GL_BACK);
3211
3212         if(ok==1) {
3213                 splitarea(sa, dir, fac);
3214                 mainqenter(DRAWEDGES, 1);
3215                 dodrawscreen= 1;                /* patch! event gets lost,,,? */
3216         }
3217 }
3218
3219 View3D *find_biggest_view3d(void)
3220 {
3221         ScrArea *sa= find_biggest_area_of_type(SPACE_VIEW3D);
3222         
3223         if (sa) {
3224                 return (View3D*) sa->spacedata.first;
3225         } else {
3226                 return NULL;
3227         }
3228 }
3229
3230 ScrArea *find_biggest_area_of_type(int spacecode)
3231 {
3232         ScrArea *sa, *biggest= NULL;
3233         int bigsize= 0;
3234         
3235         for (sa= G.curscreen->areabase.first; sa; sa= sa->next) {
3236                 if (spacecode==0 || sa->spacetype==spacecode) {
3237                         int x= sa->v3->vec.x - sa->v1->vec.x;
3238                         int y= sa->v3->vec.y - sa->v1->vec.y;
3239                         int size= x*x + y*y;
3240                 
3241                         if (!biggest || size>bigsize) {
3242                                 biggest= sa;
3243                                 bigsize= size;
3244                         }
3245                 }
3246         }
3247         
3248         return biggest;
3249 }
3250
3251 ScrArea *find_biggest_area(void)
3252 {
3253         return find_biggest_area_of_type(0);
3254 }
3255
3256 static void select_connected_scredge(bScreen *sc, ScrEdge *edge)
3257 {
3258         ScrEdge *se;
3259         ScrVert *sv;
3260         int oneselected;
3261         char dir;
3262         
3263         /* select connected, only in the right direction */
3264         /* 'dir' is the direction of EDGE */
3265
3266         if(edge->v1->vec.x==edge->v2->vec.x) dir= 'v';
3267         else dir= 'h';