fix for own mistake using freed memory with menus.
[blender.git] / source / blender / editors / interface / interface_handlers.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version. 
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * The Original Code is Copyright (C) 2008 Blender Foundation.
19  * All rights reserved.
20  * 
21  * Contributor(s): Blender Foundation
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26 /** \file blender/editors/interface/interface_handlers.c
27  *  \ingroup edinterface
28  */
29
30
31 #include <float.h>
32 #include <limits.h>
33 #include <math.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <ctype.h>
37 #include <assert.h>
38
39 #include "MEM_guardedalloc.h"
40
41 #include "DNA_sensor_types.h"
42 #include "DNA_controller_types.h"
43 #include "DNA_actuator_types.h"
44
45 #include "DNA_object_types.h"
46 #include "DNA_scene_types.h"
47
48 #include "BLI_math.h"
49 #include "BLI_blenlib.h"
50 #include "BLI_utildefines.h"
51 #include "BLI_string_cursor_utf8.h"
52
53 #include "BLF_translation.h"
54
55 #include "PIL_time.h"
56
57 #include "BKE_blender.h"
58 #include "BKE_colortools.h"
59 #include "BKE_context.h"
60 #include "BKE_idprop.h"
61 #include "BKE_report.h"
62 #include "BKE_texture.h"
63 #include "BKE_tracking.h"
64 #include "BKE_unit.h"
65
66 #include "ED_screen.h"
67 #include "ED_util.h"
68 #include "ED_keyframing.h"
69
70 #include "UI_interface.h"
71
72 #include "BLF_api.h"
73
74 #include "interface_intern.h"
75
76 #include "RNA_access.h"
77
78 #include "WM_api.h"
79 #include "WM_types.h"
80
81 /* place the mouse at the scaled down location when un-grabbing */
82 #define USE_CONT_MOUSE_CORRECT
83
84 /* proto */
85 static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to);
86 static void ui_add_link(bContext *C, uiBut *from, uiBut *to);
87
88 /***************** structs and defines ****************/
89
90 #define BUTTON_TOOLTIP_DELAY        0.500
91 #define BUTTON_FLASH_DELAY          0.020
92 #define MENU_SCROLL_INTERVAL        0.1
93 #define BUTTON_AUTO_OPEN_THRESH     0.3
94 #define BUTTON_MOUSE_TOWARDS_THRESH 1.0
95
96 typedef enum uiButtonActivateType {
97         BUTTON_ACTIVATE_OVER,
98         BUTTON_ACTIVATE,
99         BUTTON_ACTIVATE_APPLY,
100         BUTTON_ACTIVATE_TEXT_EDITING,
101         BUTTON_ACTIVATE_OPEN
102 } uiButtonActivateType;
103
104 typedef enum uiHandleButtonState {
105         BUTTON_STATE_INIT,
106         BUTTON_STATE_HIGHLIGHT,
107         BUTTON_STATE_WAIT_FLASH,
108         BUTTON_STATE_WAIT_RELEASE,
109         BUTTON_STATE_WAIT_KEY_EVENT,
110         BUTTON_STATE_NUM_EDITING,
111         BUTTON_STATE_TEXT_EDITING,
112         BUTTON_STATE_TEXT_SELECTING,
113         BUTTON_STATE_MENU_OPEN,
114         BUTTON_STATE_WAIT_DRAG,
115         BUTTON_STATE_EXIT
116 } uiHandleButtonState;
117
118 typedef struct uiHandleButtonData {
119         wmWindowManager *wm;
120         wmWindow *window;
121         ARegion *region;
122
123         int interactive;
124
125         /* overall state */
126         uiHandleButtonState state;
127         int retval;
128         /* booleans (could be made into flags) */
129         char cancel, escapecancel;
130         char applied, appliedinteractive;
131         wmTimer *flashtimer;
132
133         /* edited value */
134         char *str, *origstr;
135         double value, origvalue, startvalue;
136         float vec[3], origvec[3];
137         int togdual, togonly;
138         ColorBand *coba;
139
140         /* tooltip */
141         ARegion *tooltip;
142         wmTimer *tooltiptimer;
143         
144         /* auto open */
145         int used_mouse;
146         wmTimer *autoopentimer;
147
148         /* text selection/editing */
149         int maxlen, selextend, selstartx;
150
151         /* number editing / dragging */
152         int draglastx, draglasty;
153         int dragstartx, dragstarty;
154         int dragchange, draglock, dragsel;
155         float dragf, dragfstart;
156         CBData *dragcbd;
157
158 #ifdef USE_CONT_MOUSE_CORRECT
159         /* when ungrabbing buttons which are #ui_is_a_warp_but(), we may want to position them
160          * FLT_MAX signifies do-nothing, use #ui_block_to_window_fl() to get this into a usable space  */
161         float ungrab_mval[2];
162 #endif
163
164         /* menu open (watch uiFreeActiveButtons) */
165         uiPopupBlockHandle *menu;
166         int menuretval;
167         
168         /* search box (watch uiFreeActiveButtons) */
169         ARegion *searchbox;
170
171         /* post activate */
172         uiButtonActivateType posttype;
173         uiBut *postbut;
174 } uiHandleButtonData;
175
176 typedef struct uiAfterFunc {
177         struct uiAfterFunc *next, *prev;
178
179         uiButHandleFunc func;
180         void *func_arg1;
181         void *func_arg2;
182         void *func_arg3;
183         
184         uiButHandleNFunc funcN;
185         void *func_argN;
186
187         uiButHandleRenameFunc rename_func;
188         void *rename_arg1;
189         void *rename_orig;
190         
191         uiBlockHandleFunc handle_func;
192         void *handle_func_arg;
193         int retval;
194
195         uiMenuHandleFunc butm_func;
196         void *butm_func_arg;
197         int a2;
198
199         wmOperatorType *optype;
200         int opcontext;
201         PointerRNA *opptr;
202
203         PointerRNA rnapoin;
204         PropertyRNA *rnaprop;
205
206         bContextStore *context;
207
208         char undostr[BKE_UNDO_STR_MAX];
209
210         int autokey;
211 } uiAfterFunc;
212
213 static int ui_but_contains_pt(uiBut *but, int mx, int my);
214 static int ui_mouse_inside_button(ARegion *ar, uiBut *but, int x, int y);
215 static void button_activate_state(bContext *C, uiBut *but, uiHandleButtonState state);
216 static int ui_handler_region_menu(bContext *C, wmEvent *event, void *userdata);
217 static void ui_handle_button_activate(bContext *C, ARegion *ar, uiBut *but, uiButtonActivateType type);
218 static void button_timers_tooltip_remove(bContext *C, uiBut *but);
219
220 /* ******************** menu navigation helpers ************** */
221
222 static int ui_but_editable(uiBut *but)
223 {
224         return ELEM5(but->type, LABEL, SEPR, ROUNDBOX, LISTBOX, PROGRESSBAR);
225 }
226
227 static uiBut *ui_but_prev(uiBut *but)
228 {
229         while (but->prev) {
230                 but = but->prev;
231                 if (!ui_but_editable(but)) return but;
232         }
233         return NULL;
234 }
235
236 static uiBut *ui_but_next(uiBut *but)
237 {
238         while (but->next) {
239                 but = but->next;
240                 if (!ui_but_editable(but)) return but;
241         }
242         return NULL;
243 }
244
245 static uiBut *ui_but_first(uiBlock *block)
246 {
247         uiBut *but;
248         
249         but = block->buttons.first;
250         while (but) {
251                 if (!ui_but_editable(but)) return but;
252                 but = but->next;
253         }
254         return NULL;
255 }
256
257 static uiBut *ui_but_last(uiBlock *block)
258 {
259         uiBut *but;
260         
261         but = block->buttons.last;
262         while (but) {
263                 if (!ui_but_editable(but)) return but;
264                 but = but->prev;
265         }
266         return NULL;
267 }
268
269 static int ui_is_a_warp_but(uiBut *but)
270 {
271         if (U.uiflag & USER_CONTINUOUS_MOUSE) {
272                 if (ELEM6(but->type, NUM, NUMABS, HSVCIRCLE, TRACKPREVIEW, HSVCUBE, BUT_CURVE)) {
273                         return TRUE;
274                 }
275         }
276
277         return FALSE;
278 }
279
280 static float ui_mouse_scale_warp_factor(const short shift)
281 {
282         if (U.uiflag & USER_CONTINUOUS_MOUSE) {
283                 return shift ? 0.05f : 1.0f;
284         }
285         else {
286                 return 1.0f;
287         }
288 }
289
290 static void ui_mouse_scale_warp(uiHandleButtonData *data,
291                                 const float mx, const float my,
292                                 float *r_mx, float *r_my,
293                                 const short shift)
294 {
295         if (U.uiflag & USER_CONTINUOUS_MOUSE) {
296                 const float fac = ui_mouse_scale_warp_factor(shift);
297                 /* slow down the mouse, this is fairly picky */
298                 *r_mx = (data->dragstartx * (1.0f - fac) + mx * fac);
299                 *r_my = (data->dragstarty * (1.0f - fac) + my * fac);
300         }
301         else {
302                 *r_mx = mx;
303                 *r_my = my;
304         }
305 }
306
307 /* file selectors are exempt from utf-8 checks */
308 int ui_is_but_utf8(uiBut *but)
309 {
310         if (but->rnaprop) {
311                 const int subtype = RNA_property_subtype(but->rnaprop);
312                 return !(ELEM4(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME, PROP_BYTESTRING));
313         }
314         else {
315                 return !(but->flag & UI_BUT_NO_UTF8);
316         }
317 }
318
319 /* ********************** button apply/revert ************************/
320
321 static ListBase UIAfterFuncs = {NULL, NULL};
322
323 static void ui_apply_but_func(bContext *C, uiBut *but)
324 {
325         uiAfterFunc *after;
326         uiBlock *block = but->block;
327
328         /* these functions are postponed and only executed after all other
329          * handling is done, i.e. menus are closed, in order to avoid conflicts
330          * with these functions removing the buttons we are working with */
331
332         if (but->func || but->funcN || block->handle_func || but->rename_func ||
333             (but->type == BUTM && block->butm_func) || but->optype || but->rnaprop)
334         {
335                 after = MEM_callocN(sizeof(uiAfterFunc), "uiAfterFunc");
336
337                 if (but->func && ELEM(but, but->func_arg1, but->func_arg2)) {
338                         /* exception, this will crash due to removed button otherwise */
339                         but->func(C, but->func_arg1, but->func_arg2);
340                 }
341                 else
342                         after->func = but->func;
343
344                 after->func_arg1 = but->func_arg1;
345                 after->func_arg2 = but->func_arg2;
346                 after->func_arg3 = but->func_arg3;
347
348                 after->funcN = but->funcN;
349                 after->func_argN = MEM_dupallocN(but->func_argN);
350
351                 after->rename_func = but->rename_func;
352                 after->rename_arg1 = but->rename_arg1;
353                 after->rename_orig = but->rename_orig; /* needs free! */
354
355                 after->handle_func = block->handle_func;
356                 after->handle_func_arg = block->handle_func_arg;
357                 after->retval = but->retval;
358
359                 if (but->type == BUTM) {
360                         after->butm_func = block->butm_func;
361                         after->butm_func_arg = block->butm_func_arg;
362                         after->a2 = but->a2;
363                 }
364
365                 after->optype = but->optype;
366                 after->opcontext = but->opcontext;
367                 after->opptr = but->opptr;
368
369                 after->rnapoin = but->rnapoin;
370                 after->rnaprop = but->rnaprop;
371
372                 if (but->context)
373                         after->context = CTX_store_copy(but->context);
374
375                 but->optype = NULL;
376                 but->opcontext = 0;
377                 but->opptr = NULL;
378
379                 BLI_addtail(&UIAfterFuncs, after);
380         }
381 }
382
383 static void ui_apply_autokey_undo(bContext *C, uiBut *but)
384 {
385         Scene *scene = CTX_data_scene(C);
386         uiAfterFunc *after;
387
388         if (but->flag & UI_BUT_UNDO) {
389                 const char *str = NULL;
390
391                 /* define which string to use for undo */
392                 if (ELEM(but->type, LINK, INLINK)) str = "Add button link";
393                 else if (ELEM(but->type, MENU, ICONTEXTROW)) str = but->drawstr;
394                 else if (but->drawstr[0]) str = but->drawstr;
395                 else str = but->tip;
396
397                 /* fallback, else we don't get an undo! */
398                 if (str == NULL || str[0] == '\0') {
399                         str = "Unknown Action";
400                 }
401
402                 /* delayed, after all other funcs run, popups are closed, etc */
403                 after = MEM_callocN(sizeof(uiAfterFunc), "uiAfterFunc");
404                 BLI_strncpy(after->undostr, str, sizeof(after->undostr));
405                 BLI_addtail(&UIAfterFuncs, after);
406         }
407
408         /* try autokey */
409         ui_but_anim_autokey(C, but, scene, scene->r.cfra);
410 }
411
412 static void ui_apply_but_funcs_after(bContext *C)
413 {
414         uiAfterFunc *afterf, after;
415         PointerRNA opptr;
416         ListBase funcs;
417
418         /* copy to avoid recursive calls */
419         funcs = UIAfterFuncs;
420         UIAfterFuncs.first = UIAfterFuncs.last = NULL;
421
422         for (afterf = funcs.first; afterf; afterf = after.next) {
423                 after = *afterf; /* copy to avoid memleak on exit() */
424                 BLI_freelinkN(&funcs, afterf);
425
426                 if (after.context)
427                         CTX_store_set(C, after.context);
428
429                 if (after.opptr) {
430                         /* free in advance to avoid leak on exit */
431                         opptr = *after.opptr,
432                         MEM_freeN(after.opptr);
433                 }
434
435                 if (after.optype)
436                         WM_operator_name_call(C, after.optype->idname, after.opcontext, (after.opptr) ? &opptr : NULL);
437
438                 if (after.opptr)
439                         WM_operator_properties_free(&opptr);
440
441                 if (after.rnapoin.data)
442                         RNA_property_update(C, &after.rnapoin, after.rnaprop);
443
444                 if (after.context) {
445                         CTX_store_set(C, NULL);
446                         CTX_store_free(after.context);
447                 }
448
449                 if (after.func)
450                         after.func(C, after.func_arg1, after.func_arg2);
451                 if (after.funcN)
452                         after.funcN(C, after.func_argN, after.func_arg2);
453                 if (after.func_argN)
454                         MEM_freeN(after.func_argN);
455                 
456                 if (after.handle_func)
457                         after.handle_func(C, after.handle_func_arg, after.retval);
458                 if (after.butm_func)
459                         after.butm_func(C, after.butm_func_arg, after.a2);
460                 
461                 if (after.rename_func)
462                         after.rename_func(C, after.rename_arg1, after.rename_orig);
463                 if (after.rename_orig)
464                         MEM_freeN(after.rename_orig);
465                 
466                 if (after.undostr[0])
467                         ED_undo_push(C, after.undostr);
468         }
469 }
470
471 static void ui_apply_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data)
472 {
473         ui_apply_but_func(C, but);
474
475         data->retval = but->retval;
476         data->applied = TRUE;
477 }
478
479 static void ui_apply_but_BUTM(bContext *C, uiBut *but, uiHandleButtonData *data)
480 {
481         ui_set_but_val(but, but->hardmin);
482         ui_apply_but_func(C, but);
483
484         data->retval = but->retval;
485         data->applied = TRUE;
486 }
487
488 static void ui_apply_but_BLOCK(bContext *C, uiBut *but, uiHandleButtonData *data)
489 {
490         if (ELEM3(but->type, MENU, ICONROW, ICONTEXTROW))
491                 ui_set_but_val(but, data->value);
492
493         ui_check_but(but);
494         ui_apply_but_func(C, but);
495         data->retval = but->retval;
496         data->applied = TRUE;
497 }
498
499 static void ui_apply_but_TOG(bContext *C, uiBut *but, uiHandleButtonData *data)
500 {
501         double value;
502         int w, lvalue, push;
503         
504         /* local hack... */
505         if (but->type == BUT_TOGDUAL && data->togdual) {
506                 if (but->pointype == UI_BUT_POIN_SHORT) {
507                         but->poin += 2;
508                 }
509                 else if (but->pointype == UI_BUT_POIN_INT) {
510                         but->poin += 4;
511                 }
512         }
513         
514         value = ui_get_but_val(but);
515         lvalue = (int)value;
516         
517         if (but->bit) {
518                 w = UI_BITBUT_TEST(lvalue, but->bitnr);
519                 if (w) lvalue = UI_BITBUT_CLR(lvalue, but->bitnr);
520                 else   lvalue = UI_BITBUT_SET(lvalue, but->bitnr);
521                 
522                 if (but->type == TOGR) {
523                         if (!data->togonly) {
524                                 lvalue = 1 << (but->bitnr);
525         
526                                 ui_set_but_val(but, (double)lvalue);
527                         }
528                         else {
529                                 if (lvalue == 0) lvalue = 1 << (but->bitnr);
530                         }
531                 }
532                 
533                 ui_set_but_val(but, (double)lvalue);
534                 if (but->type == ICONTOG || but->type == ICONTOGN) ui_check_but(but);
535         }
536         else {
537                 
538                 if (value == 0.0) push = 1;
539                 else push = 0;
540                 
541                 if (ELEM3(but->type, TOGN, ICONTOGN, OPTIONN)) push = !push;
542                 ui_set_but_val(but, (double)push);
543                 if (but->type == ICONTOG || but->type == ICONTOGN) ui_check_but(but);
544         }
545         
546         /* end local hack... */
547         if (but->type == BUT_TOGDUAL && data->togdual) {
548                 if (but->pointype == UI_BUT_POIN_SHORT) {
549                         but->poin -= 2;
550                 }
551                 else if (but->pointype == UI_BUT_POIN_INT) {
552                         but->poin -= 4;
553                 }
554         }
555         
556         ui_apply_but_func(C, but);
557
558         data->retval = but->retval;
559         data->applied = TRUE;
560 }
561
562 static void ui_apply_but_ROW(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
563 {
564         uiBut *bt;
565         
566         ui_set_but_val(but, but->hardmax);
567         
568         /* states of other row buttons */
569         for (bt = block->buttons.first; bt; bt = bt->next)
570                 if (bt != but && bt->poin == but->poin && ELEM(bt->type, ROW, LISTROW))
571                         ui_check_but(bt);
572         
573         ui_apply_but_func(C, but);
574
575         data->retval = but->retval;
576         data->applied = TRUE;
577 }
578
579 static void ui_apply_but_TEX(bContext *C, uiBut *but, uiHandleButtonData *data)
580 {
581         if (!data->str)
582                 return;
583
584         ui_set_but_string(C, but, data->str);
585         ui_check_but(but);
586
587         /* give butfunc the original text too */
588         /* feature used for bone renaming, channels, etc */
589         /* afterfunc frees origstr */
590         but->rename_orig = data->origstr;
591         data->origstr = NULL;
592         ui_apply_but_func(C, but);
593
594         data->retval = but->retval;
595         data->applied = TRUE;
596 }
597
598 static void ui_apply_but_NUM(bContext *C, uiBut *but, uiHandleButtonData *data)
599 {
600         if (data->str) {
601                 if (ui_set_but_string(C, but, data->str)) {
602                         data->value = ui_get_but_val(but);
603                 }
604                 else {
605                         data->cancel = TRUE;
606                         return;
607                 }
608         }
609         else
610                 ui_set_but_val(but, data->value);
611
612         ui_check_but(but);
613         ui_apply_but_func(C, but);
614
615         data->retval = but->retval;
616         data->applied = TRUE;
617 }
618
619 static void ui_apply_but_TOG3(bContext *C, uiBut *but, uiHandleButtonData *data)
620
621         if (but->pointype == UI_BUT_POIN_SHORT) {
622                 short *sp = (short *)but->poin;
623                 
624                 if (UI_BITBUT_TEST(sp[1], but->bitnr)) {
625                         sp[1] = UI_BITBUT_CLR(sp[1], but->bitnr);
626                         sp[0] = UI_BITBUT_CLR(sp[0], but->bitnr);
627                 }
628                 else if (UI_BITBUT_TEST(sp[0], but->bitnr)) {
629                         sp[1] = UI_BITBUT_SET(sp[1], but->bitnr);
630                 }
631                 else {
632                         sp[0] = UI_BITBUT_SET(sp[0], but->bitnr);
633                 }
634         }
635         else {
636                 if (UI_BITBUT_TEST(*(but->poin + 2), but->bitnr)) {
637                         *(but->poin + 2) = UI_BITBUT_CLR(*(but->poin + 2), but->bitnr);
638                         *(but->poin)     = UI_BITBUT_CLR(*(but->poin),     but->bitnr);
639                 }
640                 else if (UI_BITBUT_TEST(*(but->poin), but->bitnr)) {
641                         *(but->poin + 2) = UI_BITBUT_SET(*(but->poin + 2), but->bitnr);
642                 }
643                 else {
644                         *(but->poin) = UI_BITBUT_SET(*(but->poin), but->bitnr);
645                 }
646         }
647         
648         ui_check_but(but);
649         ui_apply_but_func(C, but);
650         data->retval = but->retval;
651         data->applied = TRUE;
652 }
653
654 static void ui_apply_but_VEC(bContext *C, uiBut *but, uiHandleButtonData *data)
655 {
656         ui_set_but_vectorf(but, data->vec);
657         ui_check_but(but);
658         ui_apply_but_func(C, but);
659
660         data->retval = but->retval;
661         data->applied = TRUE;
662 }
663
664 static void ui_apply_but_COLORBAND(bContext *C, uiBut *but, uiHandleButtonData *data)
665 {
666         ui_apply_but_func(C, but);
667         data->retval = but->retval;
668         data->applied = TRUE;
669 }
670
671 static void ui_apply_but_CURVE(bContext *C, uiBut *but, uiHandleButtonData *data)
672 {
673         ui_apply_but_func(C, but);
674         data->retval = but->retval;
675         data->applied = TRUE;
676 }
677
678 static void ui_apply_but_IDPOIN(bContext *C, uiBut *but, uiHandleButtonData *data)
679 {
680         ui_set_but_string(C, but, data->str);
681         ui_check_but(but);
682         ui_apply_but_func(C, but);
683         data->retval = but->retval;
684         data->applied = TRUE;
685 }
686
687 #ifdef WITH_INTERNATIONAL
688 static void ui_apply_but_CHARTAB(bContext *C, uiBut *but, uiHandleButtonData *data)
689 {
690         ui_apply_but_func(C, but);
691         data->retval = but->retval;
692         data->applied = TRUE;
693 }
694 #endif
695
696 /* ****************** drag drop code *********************** */
697
698 static int ui_but_mouse_inside_icon(uiBut *but, ARegion *ar, wmEvent *event)
699 {
700         rcti rect;
701         int x = event->x, y = event->y;
702         
703         ui_window_to_block(ar, but->block, &x, &y);
704         
705         BLI_rcti_rctf_copy(&rect, &but->rect);
706         
707         if (but->imb) { 
708                 /* use button size itself */
709         }
710         else if (but->flag & UI_ICON_LEFT) {
711                 rect.xmax = rect.xmin + (BLI_rcti_size_y(&rect));
712         }
713         else {
714                 int delta = BLI_rcti_size_x(&rect) - BLI_rcti_size_y(&rect);
715                 rect.xmin += delta / 2;
716                 rect.xmax -= delta / 2;
717         }
718         
719         return BLI_rcti_isect_pt(&rect, x, y);
720 }
721
722 static int ui_but_start_drag(bContext *C, uiBut *but, uiHandleButtonData *data, wmEvent *event)
723 {
724         /* prevent other WM gestures to start while we try to drag */
725         WM_gestures_remove(C);
726
727         if (ABS(data->dragstartx - event->x) + ABS(data->dragstarty - event->y) > U.dragthreshold) {
728                 wmDrag *drag;
729                 
730                 button_activate_state(C, but, BUTTON_STATE_EXIT);
731                 data->cancel = TRUE;
732                 
733                 drag = WM_event_start_drag(C, but->icon, but->dragtype, but->dragpoin, ui_get_but_val(but));
734                 if (but->imb)
735                         WM_event_drag_image(drag, but->imb, but->imb_scale, BLI_rctf_size_x(&but->rect), BLI_rctf_size_y(&but->rect));
736                 return 1;
737         }
738         
739         return 0;
740 }
741
742 /* ********************** linklines *********************** */
743
744 static void ui_delete_active_linkline(uiBlock *block)
745 {
746         uiBut *but;
747         uiLink *link;
748         uiLinkLine *line, *nline;
749         int a, b;
750
751         for (but = block->buttons.first; but; but = but->next) {
752                 if (but->type == LINK && but->link) {
753                         for (line = but->link->lines.first; line; line = nline) {
754                                 nline = line->next;
755                                 
756                                 if (line->flag & UI_SELECT) {
757                                         BLI_remlink(&but->link->lines, line);
758                                         
759                                         link = line->from->link;
760                                         
761                                         /* are there more pointers allowed? */
762                                         if (link->ppoin) {
763                                                 
764                                                 if (*(link->totlink) == 1) {
765                                                         *(link->totlink) = 0;
766                                                         MEM_freeN(*(link->ppoin));
767                                                         *(link->ppoin) = NULL;
768                                                 }
769                                                 else {
770                                                         b = 0;
771                                                         for (a = 0; a < (*(link->totlink)); a++) {
772                                                                 
773                                                                 if ((*(link->ppoin))[a] != line->to->poin) {
774                                                                         (*(link->ppoin))[b] = (*(link->ppoin))[a];
775                                                                         b++;
776                                                                 }
777                                                         }       
778                                                         (*(link->totlink))--;
779                                                 }
780                                         }
781                                         else {
782                                                 *(link->poin) = NULL;
783                                         }
784                                         
785                                         MEM_freeN(line);
786                                 }
787                         }
788                 }
789         }
790 }
791
792
793 static uiLinkLine *ui_is_a_link(uiBut *from, uiBut *to)
794 {
795         uiLinkLine *line;
796         uiLink *link;
797         
798         link = from->link;
799         if (link) {
800                 for (line = link->lines.first; line; line = line->next) {
801                         if (line->from == from && line->to == to) {
802                                 return line;
803                         }
804                 }
805         }
806         return NULL;
807 }
808
809 /* XXX BAD BAD HACK, fixme later **************** */
810 /* Try to add an AND Controller between the sensor and the actuator logic bricks and to connect them all */
811 static void ui_add_smart_controller(bContext *C, uiBut *from, uiBut *to)
812 {
813         Object *ob = NULL;
814         bSensor *sens_iter;
815         bActuator *act_to, *act_iter;
816         bController *cont;
817         bController ***sens_from_links;
818         uiBut *tmp_but;
819
820         uiLink *link = from->link;
821
822         PointerRNA props_ptr, object_ptr;
823         
824         if (link->ppoin)
825                 sens_from_links = (bController ***)(link->ppoin);
826         else return;
827
828         act_to = (bActuator *)(to->poin);
829
830         /* (1) get the object */
831         CTX_DATA_BEGIN (C, Object *, ob_iter, selected_editable_objects)
832         {
833                 for (sens_iter = ob_iter->sensors.first; sens_iter; sens_iter = sens_iter->next) {
834                         if (&(sens_iter->links) == sens_from_links) {
835                                 ob = ob_iter;
836                                 break;
837                         }
838                 }
839                 if (ob) break;
840         } CTX_DATA_END;
841
842         if (!ob) return;
843
844         /* (2) check if the sensor and the actuator are from the same object */
845         for (act_iter = ob->actuators.first; act_iter; act_iter = (bActuator *)act_iter->next) {
846                 if (act_iter == act_to)
847                         break;
848         }
849
850         /* only works if the sensor and the actuator are from the same object */
851         if (!act_iter) return;
852         
853         /* in case the linked controller is not the active one */
854         RNA_pointer_create((ID *)ob, &RNA_Object, ob, &object_ptr);
855         
856         WM_operator_properties_create(&props_ptr, "LOGIC_OT_controller_add");
857         RNA_string_set(&props_ptr, "object", ob->id.name + 2);
858
859         /* (3) add a new controller */
860         if (WM_operator_name_call(C, "LOGIC_OT_controller_add", WM_OP_EXEC_DEFAULT, &props_ptr) & OPERATOR_FINISHED) {
861                 cont = (bController *)ob->controllers.last;
862                 cont->type = CONT_LOGIC_AND; /* Quick fix to make sure we always have an AND controller. It might be nicer to make sure the operator gives us the right one though... */
863
864                 /* (4) link the sensor->controller->actuator */
865                 tmp_but = MEM_callocN(sizeof(uiBut), "uiBut");
866                 uiSetButLink(tmp_but, (void **)&cont, (void ***)&(cont->links), &(cont->totlinks), from->link->tocode, (int)to->hardmin);
867                 tmp_but->hardmin = from->link->tocode;
868                 tmp_but->poin = (char *)cont;
869
870                 tmp_but->type = INLINK;
871                 ui_add_link(C, from, tmp_but);
872
873                 tmp_but->type = LINK;
874                 ui_add_link(C, tmp_but, to);
875
876                 /* (5) garbage collection */
877                 MEM_freeN(tmp_but->link);
878                 MEM_freeN(tmp_but);
879         }
880         WM_operator_properties_free(&props_ptr);
881 }
882
883 static void ui_add_link(bContext *C, uiBut *from, uiBut *to)
884 {
885         /* in 'from' we have to add a link to 'to' */
886         uiLink *link;
887         uiLinkLine *line;
888         void **oldppoin;
889         int a;
890         
891         if ((line = ui_is_a_link(from, to))) {
892                 line->flag |= UI_SELECT;
893                 ui_delete_active_linkline(from->block);
894                 return;
895         }
896
897         if (from->type == INLINK && to->type == INLINK) {
898                 return;
899         }
900         else if (from->type == LINK && to->type == INLINK) {
901                 if (from->link->tocode != (int)to->hardmin) {
902                         ui_add_smart_controller(C, from, to);
903                         return;
904                 }
905         }
906         else if (from->type == INLINK && to->type == LINK) {
907                 if (to->link->tocode == (int)from->hardmin) {
908                         return;
909                 }
910         }
911         
912         link = from->link;
913         
914         /* are there more pointers allowed? */
915         if (link->ppoin) {
916                 oldppoin = *(link->ppoin);
917                 
918                 (*(link->totlink))++;
919                 *(link->ppoin) = MEM_callocN(*(link->totlink) * sizeof(void *), "new link");
920                 
921                 for (a = 0; a < (*(link->totlink)) - 1; a++) {
922                         (*(link->ppoin))[a] = oldppoin[a];
923                 }
924                 (*(link->ppoin))[a] = to->poin;
925                 
926                 if (oldppoin) MEM_freeN(oldppoin);
927         }
928         else {
929                 *(link->poin) = to->poin;
930         }
931         
932 }
933
934
935 static void ui_apply_but_LINK(bContext *C, uiBut *but, uiHandleButtonData *data)
936 {
937         ARegion *ar = CTX_wm_region(C);
938         uiBut *bt;
939         
940         for (bt = but->block->buttons.first; bt; bt = bt->next) {
941                 if (ui_mouse_inside_button(ar, bt, but->linkto[0] + ar->winrct.xmin, but->linkto[1] + ar->winrct.ymin) )
942                         break;
943         }
944         if (bt && bt != but) {
945                 if (!ELEM(bt->type, LINK, INLINK) || !ELEM(but->type, LINK, INLINK))
946                         return;
947                 
948                 if (but->type == LINK) ui_add_link(C, but, bt);
949                 else ui_add_link(C, bt, but);
950
951                 ui_apply_but_func(C, but);
952                 data->retval = but->retval;
953         }
954         data->applied = TRUE;
955 }
956
957 static void ui_apply_but_IMAGE(bContext *C, uiBut *but, uiHandleButtonData *data)
958 {
959         ui_apply_but_func(C, but);
960         data->retval = but->retval;
961         data->applied = TRUE;
962 }
963
964 static void ui_apply_but_HISTOGRAM(bContext *C, uiBut *but, uiHandleButtonData *data)
965 {
966         ui_apply_but_func(C, but);
967         data->retval = but->retval;
968         data->applied = TRUE;
969 }
970
971 static void ui_apply_but_WAVEFORM(bContext *C, uiBut *but, uiHandleButtonData *data)
972 {
973         ui_apply_but_func(C, but);
974         data->retval = but->retval;
975         data->applied = TRUE;
976 }
977
978 static void ui_apply_but_TRACKPREVIEW(bContext *C, uiBut *but, uiHandleButtonData *data)
979 {
980         ui_apply_but_func(C, but);
981         data->retval = but->retval;
982         data->applied = TRUE;
983 }
984
985
986 static void ui_apply_button(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, int interactive)
987 {
988         char *editstr;
989         double *editval;
990         float *editvec;
991         ColorBand *editcoba;
992         CurveMapping *editcumap;
993
994         data->retval = 0;
995
996         /* if we cancel and have not applied yet, there is nothing to do,
997          * otherwise we have to restore the original value again */
998         if (data->cancel) {
999                 if (!data->applied)
1000                         return;
1001
1002                 if (data->str) MEM_freeN(data->str);
1003                 data->str = data->origstr;
1004                 data->origstr = NULL;
1005                 data->value = data->origvalue;
1006                 data->origvalue = 0.0;
1007                 copy_v3_v3(data->vec, data->origvec);
1008                 data->origvec[0] = data->origvec[1] = data->origvec[2] = 0.0f;
1009         }
1010         else {
1011                 /* we avoid applying interactive edits a second time
1012                  * at the end with the appliedinteractive flag */
1013                 if (interactive) {
1014                         data->appliedinteractive = TRUE;
1015                 }
1016                 else if (data->appliedinteractive) {
1017                         return;
1018                 }
1019         }
1020
1021         /* ensures we are writing actual values */
1022         editstr = but->editstr;
1023         editval = but->editval;
1024         editvec = but->editvec;
1025         editcoba = but->editcoba;
1026         editcumap = but->editcumap;
1027         but->editstr = NULL;
1028         but->editval = NULL;
1029         but->editvec = NULL;
1030         but->editcoba = NULL;
1031         but->editcumap = NULL;
1032
1033         /* handle different types */
1034         switch (but->type) {
1035                 case BUT:
1036                         ui_apply_but_BUT(C, but, data);
1037                         break;
1038                 case TEX:
1039                 case SEARCH_MENU:
1040                         ui_apply_but_TEX(C, but, data);
1041                         break;
1042                 case TOGBUT: 
1043                 case TOG: 
1044                 case TOGR: 
1045                 case ICONTOG:
1046                 case ICONTOGN:
1047                 case TOGN:
1048                 case BUT_TOGDUAL:
1049                 case OPTION:
1050                 case OPTIONN:
1051                         ui_apply_but_TOG(C, but, data);
1052                         break;
1053                 case ROW:
1054                 case LISTROW:
1055                         ui_apply_but_ROW(C, block, but, data);
1056                         break;
1057                 case SCROLL:
1058                 case NUM:
1059                 case NUMABS:
1060                 case SLI:
1061                 case NUMSLI:
1062                         ui_apply_but_NUM(C, but, data);
1063                         break;
1064                 case HSVSLI:
1065                         break;
1066                 case TOG3:      
1067                         ui_apply_but_TOG3(C, but, data);
1068                         break;
1069                 case MENU:
1070                 case ICONROW:
1071                 case ICONTEXTROW:
1072                 case BLOCK:
1073                 case PULLDOWN:
1074                         ui_apply_but_BLOCK(C, but, data);
1075                         break;
1076                 case COLOR:
1077                         if (data->cancel)
1078                                 ui_apply_but_VEC(C, but, data);
1079                         else
1080                                 ui_apply_but_BLOCK(C, but, data);
1081                         break;
1082                 case BUTM:
1083                         ui_apply_but_BUTM(C, but, data);
1084                         break;
1085                 case BUT_NORMAL:
1086                 case HSVCUBE:
1087                 case HSVCIRCLE:
1088                         ui_apply_but_VEC(C, but, data);
1089                         break;
1090                 case BUT_COLORBAND:
1091                         ui_apply_but_COLORBAND(C, but, data);
1092                         break;
1093                 case BUT_CURVE:
1094                         ui_apply_but_CURVE(C, but, data);
1095                         break;
1096                 case IDPOIN:
1097                         ui_apply_but_IDPOIN(C, but, data);
1098                         break;
1099 #ifdef WITH_INTERNATIONAL
1100                 case CHARTAB:
1101                         ui_apply_but_CHARTAB(C, but, data);
1102                         break;
1103 #endif
1104                 case KEYEVT:
1105                 case HOTKEYEVT:
1106                         ui_apply_but_BUT(C, but, data);
1107                         break;
1108                 case LINK:
1109                 case INLINK:
1110                         ui_apply_but_LINK(C, but, data);
1111                         break;
1112                 case BUT_IMAGE: 
1113                         ui_apply_but_IMAGE(C, but, data);
1114                         break;
1115                 case HISTOGRAM: 
1116                         ui_apply_but_HISTOGRAM(C, but, data);
1117                         break;
1118                 case WAVEFORM:
1119                         ui_apply_but_WAVEFORM(C, but, data);
1120                         break;
1121                 case TRACKPREVIEW:
1122                         ui_apply_but_TRACKPREVIEW(C, but, data);
1123                         break;
1124                 default:
1125                         break;
1126         }
1127
1128         but->editstr = editstr;
1129         but->editval = editval;
1130         but->editvec = editvec;
1131         but->editcoba = editcoba;
1132         but->editcumap = editcumap;
1133 }
1134
1135 /* ******************* drop event ********************  */
1136
1137 /* only call if event type is EVT_DROP */
1138 static void ui_but_drop(bContext *C, wmEvent *event, uiBut *but, uiHandleButtonData *data)
1139 {
1140         wmDrag *wmd;
1141         ListBase *drags = event->customdata; /* drop event type has listbase customdata by default */
1142         
1143         for (wmd = drags->first; wmd; wmd = wmd->next) {
1144                 if (wmd->type == WM_DRAG_ID) {
1145                         /* align these types with UI_but_active_drop_name */
1146                         if (ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
1147                                 ID *id = (ID *)wmd->poin;
1148                                 
1149                                 if (but->poin == NULL && but->rnapoin.data == NULL) {}
1150                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1151                                 BLI_strncpy(data->str, id->name + 2, data->maxlen);
1152                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1153                         }
1154                 }
1155         }
1156         
1157 }
1158
1159 /* ******************* copy and paste ********************  */
1160
1161 /* c = copy, v = paste */
1162 static void ui_but_copy_paste(bContext *C, uiBut *but, uiHandleButtonData *data, char mode)
1163 {
1164         static ColorBand but_copypaste_coba = {0};
1165         char buf[UI_MAX_DRAW_STR + 1] = {0};
1166
1167         if (mode == 'v' && but->lock  == TRUE) {
1168                 return;
1169         }
1170
1171         if (mode == 'v') {
1172                 /* extract first line from clipboard in case of multi-line copies */
1173                 char *p, *pbuf = WM_clipboard_text_get(0);
1174                 p = pbuf;
1175                 if (p) {
1176                         int i = 0;
1177                         while (*p && *p != '\r' && *p != '\n' && i < UI_MAX_DRAW_STR) {
1178                                 buf[i++] = *p;
1179                                 p++;
1180                         }
1181                         buf[i] = 0;
1182                         MEM_freeN(pbuf);
1183                 }
1184         }
1185         
1186         /* numeric value */
1187         if (ELEM4(but->type, NUM, NUMABS, NUMSLI, HSVSLI)) {
1188                 
1189                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1190                         /* pass */
1191                 }
1192                 else if (mode == 'c') {
1193                         ui_get_but_string(but, buf, sizeof(buf));
1194                         WM_clipboard_text_set(buf, 0);
1195                 }
1196                 else {
1197                         double val;
1198
1199                         if (ui_set_but_string_eval_num(C, but, buf, &val)) {
1200                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1201                                 data->value = val;
1202                                 ui_set_but_string(C, but, buf);
1203                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1204                         }
1205                 }
1206         }
1207
1208         /* RGB triple */
1209         else if (but->type == COLOR) {
1210                 float rgb[3];
1211                 
1212                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1213                         /* pass */
1214                 }
1215                 else if (mode == 'c') {
1216
1217                         ui_get_but_vectorf(but, rgb);
1218                         /* convert to linear color to do compatible copy between gamma and non-gamma */
1219                         if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
1220                                 srgb_to_linearrgb_v3_v3(rgb, rgb);
1221
1222                         BLI_snprintf(buf, sizeof(buf), "[%f, %f, %f]", rgb[0], rgb[1], rgb[2]);
1223                         WM_clipboard_text_set(buf, 0);
1224                         
1225                 }
1226                 else {
1227                         if (sscanf(buf, "[%f, %f, %f]", &rgb[0], &rgb[1], &rgb[2]) == 3) {
1228                                 /* assume linear colors in buffer */
1229                                 if (but->rnaprop && RNA_property_subtype(but->rnaprop) == PROP_COLOR_GAMMA)
1230                                         linearrgb_to_srgb_v3_v3(rgb, rgb);
1231
1232                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1233                                 ui_set_but_vectorf(but, rgb);
1234                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1235                         }
1236                 }
1237         }
1238
1239         /* text/string and ID data */
1240         else if (ELEM3(but->type, TEX, IDPOIN, SEARCH_MENU)) {
1241                 uiHandleButtonData *active_data = but->active;
1242
1243                 if (but->poin == NULL && but->rnapoin.data == NULL) {
1244                         /* pass */
1245                 }
1246                 else if (mode == 'c') {
1247                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1248                         BLI_strncpy(buf, active_data->str, UI_MAX_DRAW_STR);
1249                         WM_clipboard_text_set(active_data->str, 0);
1250                         active_data->cancel = TRUE;
1251                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1252                 }
1253                 else {
1254                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
1255
1256                         if (ui_is_but_utf8(but)) BLI_strncpy_utf8(active_data->str, buf, active_data->maxlen);
1257                         else BLI_strncpy(active_data->str, buf, active_data->maxlen);
1258
1259                         if (but->type == SEARCH_MENU) {
1260                                 /* else uiSearchboxData.active member is not updated [#26856] */
1261                                 ui_searchbox_update(C, data->searchbox, but, 1);
1262                         }
1263                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1264                 }
1265         }
1266         /* colorband (not supported by system clipboard) */
1267         else if (but->type == BUT_COLORBAND) {
1268                 if (mode == 'c') {
1269                         if (but->poin == NULL)
1270                                 return;
1271
1272                         memcpy(&but_copypaste_coba, but->poin, sizeof(ColorBand));
1273                 }
1274                 else {
1275                         if (but_copypaste_coba.tot == 0)
1276                                 return;
1277
1278                         if (!but->poin)
1279                                 but->poin = MEM_callocN(sizeof(ColorBand), "colorband");
1280
1281                         button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
1282                         memcpy(data->coba, &but_copypaste_coba, sizeof(ColorBand));
1283                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1284                 }
1285         }
1286         /* operator button (any type) */
1287         else if (but->optype) {
1288                 if (mode == 'c') {
1289                         PointerRNA *opptr;
1290                         char *str;
1291                         opptr = uiButGetOperatorPtrRNA(but); /* allocated when needed, the button owns it */
1292
1293                         str = WM_operator_pystring(C, but->optype, opptr, 0);
1294
1295                         WM_clipboard_text_set(str, 0);
1296
1297                         MEM_freeN(str);
1298                 }
1299         }
1300 }
1301
1302 /* ************* in-button text selection/editing ************* */
1303
1304
1305 static int ui_textedit_delete_selection(uiBut *but, uiHandleButtonData *data)
1306 {
1307         char *str = data->str;
1308         int len = strlen(str);
1309         int change = 0;
1310         if (but->selsta != but->selend && len) {
1311                 memmove(str + but->selsta, str + but->selend, (len - but->selend) + 1);
1312                 change = 1;
1313         }
1314         
1315         but->pos = but->selend = but->selsta;
1316         return change;
1317 }
1318
1319 /* note, but->block->aspect is used here, when drawing button style is getting scaled too */
1320 static void ui_textedit_set_cursor_pos(uiBut *but, uiHandleButtonData *data, short x)
1321 {
1322         uiStyle *style = UI_GetStyle();  // XXX pass on as arg
1323         uiFontStyle *fstyle = &style->widget;
1324         int startx = but->rect.xmin;
1325         char *origstr;
1326
1327         uiStyleFontSet(fstyle);
1328
1329         if (fstyle->kerning == 1) /* for BLF_width */
1330                 BLF_enable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
1331         
1332         origstr = MEM_callocN(sizeof(char) * data->maxlen, "ui_textedit origstr");
1333         
1334         BLI_strncpy(origstr, but->drawstr, data->maxlen);
1335         
1336         /* XXX solve generic */
1337         if (but->type == NUM || but->type == NUMSLI)
1338                 startx += (int)(0.5f * (BLI_rctf_size_y(&but->rect)));
1339         else if (ELEM(but->type, TEX, SEARCH_MENU)) {
1340                 startx += 5;
1341                 if (but->flag & UI_HAS_ICON)
1342                         startx += UI_DPI_ICON_SIZE;
1343         }
1344         
1345         /* mouse dragged outside the widget to the left */
1346         if (x < startx && but->ofs > 0) {       
1347                 int i = but->ofs;
1348
1349                 origstr[but->ofs] = 0;
1350                 
1351                 while (i > 0) {
1352                         if (BLI_str_cursor_step_prev_utf8(origstr, but->ofs, &i)) {
1353                                 /* 0.25 == scale factor for less sensitivity */
1354                                 if (BLF_width(fstyle->uifont_id, origstr + i) > (startx - x) * 0.25f) {
1355                                         break;
1356                                 }
1357                         }
1358                         else {
1359                                 break; /* unlikely but possible */
1360                         }
1361                 }
1362                 but->ofs = i;
1363                 but->pos = but->ofs;
1364         }
1365         /* mouse inside the widget */
1366         else if (x >= startx) {
1367                 int pos_i;
1368
1369                 /* keep track of previous distance from the cursor to the char */
1370                 float cdist, cdist_prev = 0.0f;
1371                 short pos_prev;
1372
1373                 const float aspect_sqrt = sqrtf(but->block->aspect);
1374                 
1375                 but->pos = pos_prev = strlen(origstr) - but->ofs;
1376
1377                 while (TRUE) {
1378                         /* XXX does not take zoom level into account */
1379                         cdist = startx + aspect_sqrt * BLF_width(fstyle->uifont_id, origstr + but->ofs);
1380
1381                         /* check if position is found */
1382                         if (cdist < x) {
1383                                 /* check is previous location was in fact closer */
1384                                 if (((float)x - cdist) > (cdist_prev - (float)x)) {
1385                                         but->pos = pos_prev;
1386                                 }
1387                                 break;
1388                         }
1389                         cdist_prev = cdist;
1390                         pos_prev   = but->pos;
1391                         /* done with tricky distance checks */
1392
1393                         pos_i = but->pos;
1394                         if (but->pos <= 0) break;
1395                         if (BLI_str_cursor_step_prev_utf8(origstr, but->ofs, &pos_i)) {
1396                                 but->pos = pos_i;
1397                                 origstr[but->pos + but->ofs] = 0;
1398                         }
1399                         else {
1400                                 break; /* unlikely but possible */
1401                         }
1402                 }
1403                 but->pos += but->ofs;
1404                 if (but->pos < 0) but->pos = 0;
1405         }
1406         
1407         if (fstyle->kerning == 1)
1408                 BLF_disable(fstyle->uifont_id, BLF_KERNING_DEFAULT);
1409         
1410         MEM_freeN(origstr);
1411 }
1412
1413 static void ui_textedit_set_cursor_select(uiBut *but, uiHandleButtonData *data, short x)
1414 {
1415         if      (x > data->selstartx) data->selextend = EXTEND_RIGHT;
1416         else if (x < data->selstartx) data->selextend = EXTEND_LEFT;
1417
1418         ui_textedit_set_cursor_pos(but, data, x);
1419
1420         if      (data->selextend == EXTEND_RIGHT) but->selend = but->pos;
1421         else if (data->selextend == EXTEND_LEFT)  but->selsta = but->pos;
1422
1423         ui_check_but(but);
1424 }
1425
1426 /* this is used for both utf8 and ascii, its meant to be used for single keys,
1427  * notice the buffer is either copied or not, so its not suitable for pasting in
1428  * - campbell */
1429 static int ui_textedit_type_buf(uiBut *but, uiHandleButtonData *data,
1430                                 const char *utf8_buf, int utf8_buf_len)
1431 {
1432         char *str;
1433         int len, changed = 0;
1434
1435         str = data->str;
1436         len = strlen(str);
1437
1438         if (len - (but->selend - but->selsta) + 1 <= data->maxlen) {
1439                 int step = utf8_buf_len;
1440
1441                 /* type over the current selection */
1442                 if ((but->selend - but->selsta) > 0) {
1443                         changed = ui_textedit_delete_selection(but, data);
1444                         len = strlen(str);
1445                 }
1446
1447                 if (len + step < data->maxlen) {
1448                         memmove(&str[but->pos + step], &str[but->pos], (len + 1) - but->pos);
1449                         memcpy(&str[but->pos], utf8_buf, step * sizeof(char));
1450                         but->pos += step;
1451                         changed = 1;
1452                 }
1453         }
1454
1455         return changed;
1456 }
1457
1458 static int ui_textedit_type_ascii(uiBut *but, uiHandleButtonData *data, char ascii)
1459 {
1460         char buf[2] = {ascii, '\0'};
1461
1462         if (ui_is_but_utf8(but) && (BLI_str_utf8_size(buf) == -1)) {
1463                 printf("%s: entering invalid ascii char into an ascii key (%d)\n",
1464                        __func__, (int)(unsigned char)ascii);
1465
1466                 return 0;
1467         }
1468
1469         /* in some cases we want to allow invalid utf8 chars */
1470         return ui_textedit_type_buf(but, data, buf, 1);
1471 }
1472
1473 static void ui_textedit_move(uiBut *but, uiHandleButtonData *data, strCursorJumpDirection direction,
1474                              int select, strCursorJumpType jump)
1475 {
1476         const char *str = data->str;
1477         const int len = strlen(str);
1478         const int pos_prev = but->pos;
1479         const int has_sel = (but->selend - but->selsta) > 0;
1480
1481         ui_check_but(but);
1482
1483         /* special case, quit selection and set cursor */
1484         if (has_sel && !select) {
1485                 if (jump == STRCUR_JUMP_ALL) {
1486                         but->selsta = but->selend = but->pos = direction ? len : 0;
1487                 }
1488                 else {
1489                         if (direction) {
1490                                 but->selsta = but->pos = but->selend;
1491                         }
1492                         else {
1493                                 but->pos = but->selend = but->selsta;
1494                         }
1495                 }
1496                 data->selextend = 0;
1497         }
1498         else {
1499                 int pos_i = but->pos;
1500                 BLI_str_cursor_step_utf8(str, len, &pos_i, direction, jump);
1501                 but->pos = pos_i;
1502
1503                 if (select) {
1504                         /* existing selection */
1505                         if (has_sel) {
1506
1507                                 if (data->selextend == 0) {
1508                                         data->selextend = EXTEND_RIGHT;
1509                                 }
1510
1511                                 if (direction) {
1512                                         if (data->selextend == EXTEND_RIGHT) {
1513                                                 but->selend = but->pos;
1514                                         }
1515                                         else {
1516                                                 but->selsta = but->pos;
1517                                         }
1518                                 }
1519                                 else {
1520                                         if (data->selextend == EXTEND_LEFT) {
1521                                                 but->selsta = but->pos;
1522                                         }
1523                                         else {
1524                                                 but->selend = but->pos;
1525                                         }
1526                                 }
1527
1528                                 if (but->selend < but->selsta) {
1529                                         SWAP(short, but->selsta, but->selend);
1530                                         data->selextend = (data->selextend == EXTEND_RIGHT) ? EXTEND_LEFT : EXTEND_RIGHT;
1531                                 }
1532
1533                         } /* new selection */
1534                         else {
1535                                 if (direction) {
1536                                         data->selextend = EXTEND_RIGHT;
1537                                         but->selend = but->pos;
1538                                         but->selsta = pos_prev;
1539                                 }
1540                                 else {
1541                                         data->selextend = EXTEND_LEFT;
1542                                         but->selend = pos_prev;
1543                                         but->selsta = but->pos;
1544                                 }
1545                         }
1546                 }
1547         }
1548 }
1549
1550 static int ui_textedit_delete(uiBut *but, uiHandleButtonData *data, int direction, strCursorJumpType jump)
1551 {
1552         char *str = data->str;
1553         const int len = strlen(str);
1554
1555         int changed = 0;
1556
1557         if (jump == STRCUR_JUMP_ALL) {
1558                 if (len) changed = 1;
1559                 str[0] = '\0';
1560                 but->pos = 0;
1561         }
1562         else if (direction) { /* delete */
1563                 if ((but->selend - but->selsta) > 0) {
1564                         changed = ui_textedit_delete_selection(but, data);
1565                 }
1566                 else if (but->pos >= 0 && but->pos < len) {
1567                         int pos = but->pos;
1568                         int step;
1569                         BLI_str_cursor_step_utf8(str, len, &pos, direction, jump);
1570                         step = pos - but->pos;
1571                         memmove(&str[but->pos], &str[but->pos + step], (len + 1) - but->pos);
1572                         changed = 1;
1573                 }
1574         }
1575         else { /* backspace */
1576                 if (len != 0) {
1577                         if ((but->selend - but->selsta) > 0) {
1578                                 changed = ui_textedit_delete_selection(but, data);
1579                         }
1580                         else if (but->pos > 0) {
1581                                 int pos = but->pos;
1582                                 int step;
1583
1584                                 BLI_str_cursor_step_utf8(str, len, &pos, direction, jump);
1585                                 step = but->pos - pos;
1586                                 memmove(&str[but->pos - step], &str[but->pos], (len + 1) - but->pos);
1587                                 but->pos -= step;
1588                                 changed = 1;
1589                         }
1590                 } 
1591         }
1592
1593         return changed;
1594 }
1595
1596 static int ui_textedit_autocomplete(bContext *C, uiBut *but, uiHandleButtonData *data)
1597 {
1598         char *str;
1599         int changed = 1;
1600
1601         str = data->str;
1602
1603         if (data->searchbox)
1604                 ui_searchbox_autocomplete(C, data->searchbox, but, data->str);
1605         else
1606                 but->autocomplete_func(C, str, but->autofunc_arg);
1607
1608         but->pos = strlen(str);
1609         but->selsta = but->selend = but->pos;
1610
1611         return changed;
1612 }
1613
1614 static int ui_textedit_copypaste(uiBut *but, uiHandleButtonData *data, int paste, int copy, int cut)
1615 {
1616         char buf[UI_MAX_DRAW_STR] = {0};
1617         char *str, *p, *pbuf;
1618         int len, x, i, changed = 0;
1619
1620         str = data->str;
1621         len = strlen(str);
1622         
1623         /* paste */
1624         if (paste) {
1625                 /* TODO, ensure UTF8 ui_is_but_utf8() - campbell */
1626                 /* extract the first line from the clipboard */
1627                 p = pbuf = WM_clipboard_text_get(0);
1628
1629                 if (p && p[0]) {
1630                         unsigned int y;
1631                         i = 0;
1632                         while (*p && *p != '\r' && *p != '\n' && i < UI_MAX_DRAW_STR - 1) {
1633                                 buf[i++] = *p;
1634                                 p++;
1635                         }
1636                         buf[i] = 0;
1637
1638                         /* paste over the current selection */
1639                         if ((but->selend - but->selsta) > 0) {
1640                                 ui_textedit_delete_selection(but, data);
1641                                 len = strlen(str);
1642                         }
1643                         
1644                         for (y = 0; y < strlen(buf); y++) {
1645                                 /* add contents of buffer */
1646                                 if (len + 1 < data->maxlen) {
1647                                         for (x = data->maxlen; x > but->pos; x--)
1648                                                 str[x] = str[x - 1];
1649                                         str[but->pos] = buf[y];
1650                                         but->pos++; 
1651                                         len++;
1652                                         str[len] = '\0';
1653                                 }
1654                         }
1655
1656                         changed = 1;
1657                 }
1658
1659                 if (pbuf) {
1660                         MEM_freeN(pbuf);
1661                 }
1662         }
1663         /* cut & copy */
1664         else if (copy || cut) {
1665                 /* copy the contents to the copypaste buffer */
1666                 for (x = but->selsta; x <= but->selend; x++) {
1667                         if (x == but->selend)
1668                                 buf[x] = '\0';
1669                         else
1670                                 buf[(x - but->selsta)] = str[x];
1671                 }
1672
1673                 WM_clipboard_text_set(buf, 0);
1674                 
1675                 /* for cut only, delete the selection afterwards */
1676                 if (cut)
1677                         if ((but->selend - but->selsta) > 0)
1678                                 changed = ui_textedit_delete_selection(but, data);
1679         } 
1680
1681         return changed;
1682 }
1683
1684 static void ui_textedit_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
1685 {
1686         int len;
1687
1688         if (data->str) {
1689                 MEM_freeN(data->str);
1690                 data->str = NULL;
1691         }
1692
1693         /* retrieve string */
1694         data->maxlen = ui_get_but_string_max_length(but);
1695         data->str = MEM_callocN(sizeof(char) * data->maxlen + 1, "textedit str");
1696         ui_get_but_string(but, data->str, data->maxlen);
1697
1698         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) {
1699                 ui_convert_to_unit_alt_name(but, data->str, data->maxlen);
1700         }
1701
1702         /* won't change from now on */
1703         len = strlen(data->str);
1704
1705         data->origstr = BLI_strdupn(data->str, len);
1706         data->selextend = 0;
1707         data->selstartx = 0;
1708
1709         /* set cursor pos to the end of the text */
1710         but->editstr = data->str;
1711         but->pos = len;
1712         but->selsta = 0;
1713         but->selend = len;
1714
1715         /* optional searchbox */
1716         if (but->type == SEARCH_MENU) {
1717                 data->searchbox = ui_searchbox_create(C, data->region, but);
1718                 ui_searchbox_update(C, data->searchbox, but, 1); /* 1= reset */
1719         }
1720         
1721         ui_check_but(but);
1722         
1723         WM_cursor_modal(CTX_wm_window(C), BC_TEXTEDITCURSOR);
1724 }
1725
1726 static void ui_textedit_end(bContext *C, uiBut *but, uiHandleButtonData *data)
1727 {
1728         if (but) {
1729                 if (ui_is_but_utf8(but)) {
1730                         int strip = BLI_utf8_invalid_strip(but->editstr, strlen(but->editstr));
1731                         /* not a file?, strip non utf-8 chars */
1732                         if (strip) {
1733                                 /* wont happen often so isn't that annoying to keep it here for a while */
1734                                 printf("%s: invalid utf8 - stripped chars %d\n", __func__, strip);
1735                         }
1736                 }
1737                 
1738                 if (data->searchbox) {
1739                         if (data->cancel == 0)
1740                                 ui_searchbox_apply(but, data->searchbox);
1741
1742                         ui_searchbox_free(C, data->searchbox);
1743                         data->searchbox = NULL;
1744                 }
1745                 
1746                 but->editstr = NULL;
1747                 but->pos = -1;
1748         }
1749         
1750         WM_cursor_restore(CTX_wm_window(C));
1751 }
1752
1753 static void ui_textedit_next_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
1754 {
1755         uiBut *but;
1756
1757         /* label and roundbox can overlap real buttons (backdrops...) */
1758         if (ELEM4(actbut->type, LABEL, SEPR, ROUNDBOX, LISTBOX))
1759                 return;
1760
1761         for (but = actbut->next; but; but = but->next) {
1762                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, HSVSLI, IDPOIN, SEARCH_MENU)) {
1763                         if (!(but->flag & UI_BUT_DISABLED)) {
1764                                 data->postbut = but;
1765                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
1766                                 return;
1767                         }
1768                 }
1769         }
1770         for (but = block->buttons.first; but != actbut; but = but->next) {
1771                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, HSVSLI, IDPOIN, SEARCH_MENU)) {
1772                         if (!(but->flag & UI_BUT_DISABLED)) {
1773                                 data->postbut = but;
1774                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
1775                                 return;
1776                         }
1777                 }
1778         }
1779 }
1780
1781 static void ui_textedit_prev_but(uiBlock *block, uiBut *actbut, uiHandleButtonData *data)
1782 {
1783         uiBut *but;
1784
1785         /* label and roundbox can overlap real buttons (backdrops...) */
1786         if (ELEM4(actbut->type, LABEL, SEPR, ROUNDBOX, LISTBOX))
1787                 return;
1788
1789         for (but = actbut->prev; but; but = but->prev) {
1790                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, HSVSLI, IDPOIN, SEARCH_MENU)) {
1791                         if (!(but->flag & UI_BUT_DISABLED)) {
1792                                 data->postbut = but;
1793                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
1794                                 return;
1795                         }
1796                 }
1797         }
1798         for (but = block->buttons.last; but != actbut; but = but->prev) {
1799                 if (ELEM7(but->type, TEX, NUM, NUMABS, NUMSLI, HSVSLI, IDPOIN, SEARCH_MENU)) {
1800                         if (!(but->flag & UI_BUT_DISABLED)) {
1801                                 data->postbut = but;
1802                                 data->posttype = BUTTON_ACTIVATE_TEXT_EDITING;
1803                                 return;
1804                         }
1805                 }
1806         }
1807 }
1808
1809
1810 static void ui_do_but_textedit(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, wmEvent *event)
1811 {
1812         int mx, my, changed = 0, inbox = 0, update = 0, retval = WM_UI_HANDLER_CONTINUE;
1813
1814         switch (event->type) {
1815                 case WHEELUPMOUSE:
1816                 case WHEELDOWNMOUSE:
1817                 case MOUSEMOVE:
1818                         if (data->searchbox)
1819                                 ui_searchbox_event(C, data->searchbox, but, event);
1820                         
1821                         break;
1822                 case RIGHTMOUSE:
1823                 case ESCKEY:
1824                         data->cancel = TRUE;
1825                         data->escapecancel = TRUE;
1826                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1827                         retval = WM_UI_HANDLER_BREAK;
1828                         break;
1829                 case LEFTMOUSE:
1830                 {
1831                         /* exit on LMB only on RELEASE for searchbox, to mimic other popups, and allow multiple menu levels */
1832                         if (data->searchbox)
1833                                 inbox = ui_searchbox_inside(data->searchbox, event->x, event->y);
1834
1835                         if (event->val == KM_PRESS) {
1836                                 mx = event->x;
1837                                 my = event->y;
1838                                 ui_window_to_block(data->region, block, &mx, &my);
1839
1840                                 if (ui_but_contains_pt(but, mx, my)) {
1841                                         ui_textedit_set_cursor_pos(but, data, mx);
1842                                         but->selsta = but->selend = but->pos;
1843                                         data->selstartx = mx;
1844
1845                                         button_activate_state(C, but, BUTTON_STATE_TEXT_SELECTING);
1846                                         retval = WM_UI_HANDLER_BREAK;
1847                                 }
1848                                 else if (inbox == 0) {
1849                                         /* if searchbox, click outside will cancel */
1850                                         if (data->searchbox)
1851                                                 data->cancel = data->escapecancel = TRUE;
1852                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1853                                         retval = WM_UI_HANDLER_BREAK;
1854                                 }
1855                         }
1856                         else if (inbox) {
1857                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1858                                 retval = WM_UI_HANDLER_BREAK;
1859                         }
1860                         break;
1861                 }
1862         }
1863
1864         if (event->val == KM_PRESS) {
1865                 switch (event->type) {
1866                         case VKEY:
1867                         case XKEY:
1868                         case CKEY:
1869                                 if (event->ctrl || event->oskey) {
1870                                         if (event->type == VKEY)
1871                                                 changed = ui_textedit_copypaste(but, data, 1, 0, 0);
1872                                         else if (event->type == CKEY)
1873                                                 changed = ui_textedit_copypaste(but, data, 0, 1, 0);
1874                                         else if (event->type == XKEY)
1875                                                 changed = ui_textedit_copypaste(but, data, 0, 0, 1);
1876
1877                                         retval = WM_UI_HANDLER_BREAK;
1878                                 }
1879                                 break;
1880                         case RIGHTARROWKEY:
1881                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT,
1882                                                  event->shift, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
1883                                 retval = WM_UI_HANDLER_BREAK;
1884                                 break;
1885                         case LEFTARROWKEY:
1886                                 ui_textedit_move(but, data, STRCUR_DIR_PREV,
1887                                                  event->shift, event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
1888                                 retval = WM_UI_HANDLER_BREAK;
1889                                 break;
1890                         case DOWNARROWKEY:
1891                                 if (data->searchbox) {
1892                                         ui_searchbox_event(C, data->searchbox, but, event);
1893                                         break;
1894                                 }
1895                         /* pass on purposedly */
1896                         case ENDKEY:
1897                                 ui_textedit_move(but, data, STRCUR_DIR_NEXT,
1898                                                  event->shift, STRCUR_JUMP_ALL);
1899                                 retval = WM_UI_HANDLER_BREAK;
1900                                 break;
1901                         case UPARROWKEY:
1902                                 if (data->searchbox) {
1903                                         ui_searchbox_event(C, data->searchbox, but, event);
1904                                         break;
1905                                 }
1906                         /* pass on purposedly */
1907                         case HOMEKEY:
1908                                 ui_textedit_move(but, data, STRCUR_DIR_PREV,
1909                                                  event->shift, STRCUR_JUMP_ALL);
1910                                 retval = WM_UI_HANDLER_BREAK;
1911                                 break;
1912                         case PADENTER:
1913                         case RETKEY:
1914                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
1915                                 retval = WM_UI_HANDLER_BREAK;
1916                                 break;
1917                         case DELKEY:
1918                                 changed = ui_textedit_delete(but, data, 1,
1919                                                              event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE);
1920                                 retval = WM_UI_HANDLER_BREAK;
1921                                 break;
1922
1923                         case BACKSPACEKEY:
1924                                 changed = ui_textedit_delete(but, data, 0,
1925                                                              event->shift ? STRCUR_JUMP_ALL : (event->ctrl ? STRCUR_JUMP_DELIM : STRCUR_JUMP_NONE));
1926                                 retval = WM_UI_HANDLER_BREAK;
1927                                 break;
1928                                 
1929                         case TABKEY:
1930                                 /* there is a key conflict here, we can't tab with autocomplete */
1931                                 if (but->autocomplete_func || data->searchbox) {
1932                                         changed = ui_textedit_autocomplete(C, but, data);
1933                                         update = 1; /* do live update for tab key */
1934                                 }
1935                                 /* the hotkey here is not well defined, was G.qual so we check all */
1936                                 else if (event->shift || event->ctrl || event->alt || event->oskey) {
1937                                         ui_textedit_prev_but(block, but, data);
1938                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1939                                 }
1940                                 else {
1941                                         ui_textedit_next_but(block, but, data);
1942                                         button_activate_state(C, but, BUTTON_STATE_EXIT);
1943                                 }
1944                                 retval = WM_UI_HANDLER_BREAK;
1945                                 break;
1946                 }
1947
1948                 if ((event->ascii || event->utf8_buf[0]) && (retval == WM_UI_HANDLER_CONTINUE)) {
1949                         char ascii = event->ascii;
1950                         const char *utf8_buf = event->utf8_buf;
1951
1952                         /* exception that's useful for number buttons, some keyboard
1953                          * numpads have a comma instead of a period */
1954                         if (ELEM3(but->type, NUM, NUMABS, NUMSLI)) { /* could use data->min*/
1955                                 if (event->type == PADPERIOD && ascii == ',') {
1956                                         ascii = '.';
1957                                         utf8_buf = NULL; /* force ascii fallback */
1958                                 }
1959                         }
1960
1961                         if (utf8_buf && utf8_buf[0]) {
1962                                 int utf8_buf_len = BLI_str_utf8_size(utf8_buf);
1963                                 /* keep this printf until utf8 is well tested */
1964                                 if (utf8_buf_len != 1) {
1965                                         printf("%s: utf8 char '%.*s'\n", __func__, utf8_buf_len, utf8_buf);
1966                                 }
1967
1968                                 // strcpy(utf8_buf, "12345");
1969                                 changed = ui_textedit_type_buf(but, data, event->utf8_buf, utf8_buf_len);
1970                         }
1971                         else {
1972                                 changed = ui_textedit_type_ascii(but, data, ascii);
1973                         }
1974
1975                         retval = WM_UI_HANDLER_BREAK;
1976                         
1977                 }
1978                 /* textbutton with magnifier icon: do live update for search button */
1979                 if (but->icon == ICON_VIEWZOOM)
1980                         update = 1;
1981         }
1982
1983         if (changed) {
1984                 /* only update when typing for TAB key */
1985                 if (update && data->interactive) {
1986                         ui_apply_button(C, block, but, data, 1);
1987                 }
1988                 else {
1989                         ui_check_but(but);
1990                 }
1991                 but->changed = TRUE;
1992                 
1993                 if (data->searchbox)
1994                         ui_searchbox_update(C, data->searchbox, but, 1);  /* 1 = reset */
1995         }
1996
1997         if (changed || (retval == WM_UI_HANDLER_BREAK))
1998                 ED_region_tag_redraw(data->region);
1999 }
2000
2001 static void ui_do_but_textedit_select(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, wmEvent *event)
2002 {
2003         int mx, my, retval = WM_UI_HANDLER_CONTINUE;
2004
2005         switch (event->type) {
2006                 case MOUSEMOVE:
2007                 {
2008                         mx = event->x;
2009                         my = event->y;
2010                         ui_window_to_block(data->region, block, &mx, &my);
2011
2012                         ui_textedit_set_cursor_select(but, data, mx);
2013                         retval = WM_UI_HANDLER_BREAK;
2014                         break;
2015                 }
2016                 case LEFTMOUSE:
2017                         if (event->val == KM_RELEASE)
2018                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2019                         retval = WM_UI_HANDLER_BREAK;
2020                         break;
2021         }
2022
2023         if (retval == WM_UI_HANDLER_BREAK) {
2024                 ui_check_but(but);
2025                 ED_region_tag_redraw(data->region);
2026         }
2027 }
2028
2029 /* ************* number editing for various types ************* */
2030
2031 static void ui_numedit_begin(uiBut *but, uiHandleButtonData *data)
2032 {
2033         if (but->type == BUT_CURVE) {
2034                 but->editcumap = (CurveMapping *)but->poin;
2035         }
2036         else if (but->type == BUT_COLORBAND) {
2037                 data->coba = (ColorBand *)but->poin;
2038                 but->editcoba = data->coba;
2039         }
2040         else if (ELEM3(but->type, BUT_NORMAL, HSVCUBE, HSVCIRCLE)) {
2041                 ui_get_but_vectorf(but, data->origvec);
2042                 copy_v3_v3(data->vec, data->origvec);
2043                 but->editvec = data->vec;
2044         }
2045         else {
2046                 float softrange, softmin, softmax;
2047
2048                 data->startvalue = ui_get_but_val(but);
2049                 data->origvalue = data->startvalue;
2050                 data->value = data->origvalue;
2051                 but->editval = &data->value;
2052
2053                 softmin = but->softmin;
2054                 softmax = but->softmax;
2055                 softrange = softmax - softmin;
2056
2057                 data->dragfstart = (softrange == 0.0f) ? 0.0f : ((float)data->value - softmin) / softrange;
2058                 data->dragf = data->dragfstart;
2059         }
2060
2061         data->dragchange = 0;
2062         data->draglock = 1;
2063 }
2064
2065 static void ui_numedit_end(uiBut *but, uiHandleButtonData *data)
2066 {
2067         but->editval = NULL;
2068         but->editvec = NULL;
2069         but->editcoba = NULL;
2070         but->editcumap = NULL;
2071
2072         data->dragstartx = 0;
2073         data->draglastx = 0;
2074         data->dragchange = 0;
2075         data->dragcbd = NULL;
2076         data->dragsel = 0;
2077 }
2078
2079 static void ui_numedit_apply(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data)
2080 {
2081         if (data->interactive) {
2082                 ui_apply_button(C, block, but, data, 1);
2083         }
2084         else {
2085                 ui_check_but(but);
2086         }
2087
2088         ED_region_tag_redraw(data->region);
2089 }
2090
2091 /* ****************** menu opening for various types **************** */
2092
2093 static void ui_blockopen_begin(bContext *C, uiBut *but, uiHandleButtonData *data)
2094 {
2095         uiBlockCreateFunc func = NULL;
2096         uiBlockHandleCreateFunc handlefunc = NULL;
2097         uiMenuCreateFunc menufunc = NULL;
2098         char *menustr = NULL;
2099         void *arg = NULL;
2100
2101         switch (but->type) {
2102                 case BLOCK:
2103                 case PULLDOWN:
2104                         if (but->menu_create_func) {
2105                                 menufunc = but->menu_create_func;
2106                                 arg = but->poin;
2107                         }
2108                         else {
2109                                 func = but->block_create_func;
2110                                 arg = but->poin ? but->poin : but->func_argN;
2111                         }
2112                         break;
2113                 case MENU:
2114                         if (but->menu_create_func) {
2115                                 menufunc = but->menu_create_func;
2116                                 arg = but->poin;
2117                         }
2118                         else {
2119                                 data->origvalue = ui_get_but_val(but);
2120                                 data->value = data->origvalue;
2121                                 but->editval = &data->value;
2122
2123                                 menustr = but->str;
2124                         }
2125                         break;
2126                 case ICONROW:
2127                         menufunc = ui_block_func_ICONROW;
2128                         arg = but;
2129                         break;
2130                 case ICONTEXTROW:
2131                         menufunc = ui_block_func_ICONTEXTROW;
2132                         arg = but;
2133                         break;
2134                 case COLOR:
2135                         ui_get_but_vectorf(but, data->origvec);
2136                         copy_v3_v3(data->vec, data->origvec);
2137                         but->editvec = data->vec;
2138
2139                         handlefunc = ui_block_func_COLOR;
2140                         arg = but;
2141                         break;
2142
2143                         /* quiet warnings for unhandled types */
2144                 default:
2145                         break;
2146         }
2147
2148         if (func || handlefunc) {
2149                 data->menu = ui_popup_block_create(C, data->region, but, func, handlefunc, arg);
2150                 if (but->block->handle)
2151                         data->menu->popup = but->block->handle->popup;
2152         }
2153         else if (menufunc || menustr) {
2154                 data->menu = ui_popup_menu_create(C, data->region, but, menufunc, arg, menustr);
2155                 if (but->block->handle)
2156                         data->menu->popup = but->block->handle->popup;
2157         }
2158
2159         /* this makes adjacent blocks auto open from now on */
2160         //if (but->block->auto_open ==0 ) but->block->auto_open = 1;
2161 }
2162
2163 static void ui_blockopen_end(bContext *C, uiBut *but, uiHandleButtonData *data)
2164 {
2165         if (but) {
2166                 but->editval = NULL;
2167                 but->editvec = NULL;
2168
2169                 but->block->auto_open_last = PIL_check_seconds_timer();
2170         }
2171
2172         if (data->menu) {
2173                 ui_popup_block_free(C, data->menu);
2174                 data->menu = NULL;
2175         }
2176 }
2177
2178 int ui_button_open_menu_direction(uiBut *but)
2179 {
2180         uiHandleButtonData *data = but->active;
2181
2182         if (data && data->menu)
2183                 return data->menu->direction;
2184         
2185         return 0;
2186 }
2187
2188 /* ***************** events for different button types *************** */
2189
2190 static int ui_do_but_BUT(bContext *C, uiBut *but, uiHandleButtonData *data, wmEvent *event)
2191 {
2192         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2193                 if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
2194                         button_activate_state(C, but, BUTTON_STATE_WAIT_RELEASE);
2195                         return WM_UI_HANDLER_BREAK;
2196                 }
2197                 else if (event->type == LEFTMOUSE && but->block->handle) {
2198                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2199                         return WM_UI_HANDLER_BREAK;
2200                 }
2201                 else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS) {
2202                         button_activate_state(C, but, BUTTON_STATE_WAIT_FLASH);
2203                         return WM_UI_HANDLER_BREAK;
2204                 }
2205         }
2206         else if (data->state == BUTTON_STATE_WAIT_RELEASE) {
2207                 if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
2208                         if (!(but->flag & UI_SELECT))
2209                                 data->cancel = TRUE;
2210                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2211                         return WM_UI_HANDLER_BREAK;
2212                 }
2213         }
2214
2215         return WM_UI_HANDLER_CONTINUE;
2216 }
2217
2218 static int ui_do_but_HOTKEYEVT(bContext *C, uiBut *but, uiHandleButtonData *data, wmEvent *event)
2219 {
2220         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2221                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2222                         but->drawstr[0] = 0;
2223                         but->modifier_key = 0;
2224                         button_activate_state(C, but, BUTTON_STATE_WAIT_KEY_EVENT);
2225                         return WM_UI_HANDLER_BREAK;
2226                 }
2227         }
2228         else if (data->state == BUTTON_STATE_WAIT_KEY_EVENT) {
2229                 
2230                 if (event->type == MOUSEMOVE)
2231                         return WM_UI_HANDLER_CONTINUE;
2232                 
2233                 if (event->type == LEFTMOUSE && event->val == KM_PRESS) {
2234                         /* only cancel if click outside the button */
2235                         if (ui_mouse_inside_button(but->active->region, but, event->x, event->y) == 0) {
2236                                 /* data->cancel doesnt work, this button opens immediate */
2237                                 if (but->flag & UI_BUT_IMMEDIATE)
2238                                         ui_set_but_val(but, 0);
2239                                 else
2240                                         data->cancel = TRUE;
2241                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2242                                 return WM_UI_HANDLER_BREAK;
2243                         }
2244                 }
2245                 
2246                 /* always set */
2247                 but->modifier_key = 0;
2248                 if (event->shift) but->modifier_key |= KM_SHIFT;
2249                 if (event->alt) but->modifier_key |= KM_ALT;
2250                 if (event->ctrl) but->modifier_key |= KM_CTRL;
2251                 if (event->oskey) but->modifier_key |= KM_OSKEY;
2252
2253                 ui_check_but(but);
2254                 ED_region_tag_redraw(data->region);
2255                         
2256                 if (event->val == KM_PRESS) {
2257                         if (ISHOTKEY(event->type)) { 
2258                                 
2259                                 if (WM_key_event_string(event->type)[0])
2260                                         ui_set_but_val(but, event->type);
2261                                 else
2262                                         data->cancel = TRUE;
2263                                 
2264                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2265                                 return WM_UI_HANDLER_BREAK;
2266                         }
2267                         else if (event->type == ESCKEY) {
2268                                 data->cancel = TRUE;
2269                                 data->escapecancel = TRUE;
2270                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2271                         }
2272                         
2273                 }
2274         }
2275         
2276         return WM_UI_HANDLER_CONTINUE;
2277 }
2278
2279 static int ui_do_but_KEYEVT(bContext *C, uiBut *but, uiHandleButtonData *data, wmEvent *event)
2280 {
2281         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2282                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2283                         button_activate_state(C, but, BUTTON_STATE_WAIT_KEY_EVENT);
2284                         return WM_UI_HANDLER_BREAK;
2285                 }
2286         }
2287         else if (data->state == BUTTON_STATE_WAIT_KEY_EVENT) {
2288                 if (event->type == MOUSEMOVE)
2289                         return WM_UI_HANDLER_CONTINUE;
2290
2291                 if (event->val == KM_PRESS) {
2292                         if (WM_key_event_string(event->type)[0])
2293                                 ui_set_but_val(but, event->type);
2294                         else
2295                                 data->cancel = TRUE;
2296
2297                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2298                 }
2299         }
2300
2301         return WM_UI_HANDLER_CONTINUE;
2302 }
2303
2304 static int ui_do_but_TEX(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, wmEvent *event)
2305 {
2306         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2307                 if (ELEM(event->type, LEFTMOUSE, EVT_BUT_OPEN) && event->val == KM_PRESS) {
2308                         if (but->dt == UI_EMBOSSN && !event->ctrl) {
2309                                 /* pass */
2310                         }
2311                         else {
2312                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2313                                 return WM_UI_HANDLER_BREAK;
2314                         }
2315                 }
2316         }
2317         else if (data->state == BUTTON_STATE_TEXT_EDITING) {
2318                 ui_do_but_textedit(C, block, but, data, event);
2319                 return WM_UI_HANDLER_BREAK;
2320         }
2321         else if (data->state == BUTTON_STATE_TEXT_SELECTING) {
2322                 ui_do_but_textedit_select(C, block, but, data, event);
2323                 return WM_UI_HANDLER_BREAK;
2324         }
2325
2326         return WM_UI_HANDLER_CONTINUE;
2327 }
2328
2329 static int ui_do_but_TOG(bContext *C, uiBut *but, uiHandleButtonData *data, wmEvent *event)
2330 {
2331         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2332                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2333                         data->togdual = event->ctrl;
2334                         data->togonly = !event->shift;
2335                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2336                         return WM_UI_HANDLER_BREAK;
2337                 }
2338         }
2339         return WM_UI_HANDLER_CONTINUE;
2340 }
2341
2342 static int ui_do_but_EXIT(bContext *C, uiBut *but, uiHandleButtonData *data, wmEvent *event)
2343 {
2344         
2345         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2346
2347                 /* first handle click on icondrag type button */
2348                 if (event->type == LEFTMOUSE && but->dragpoin) {
2349                         if (ui_but_mouse_inside_icon(but, data->region, event)) {
2350                                 
2351                                 /* tell the button to wait and keep checking further events to
2352                                  * see if it should start dragging */
2353                                 button_activate_state(C, but, BUTTON_STATE_WAIT_DRAG);
2354                                 data->dragstartx = event->x;
2355                                 data->dragstarty = event->y;
2356                                 return WM_UI_HANDLER_CONTINUE;
2357                         }
2358                 }
2359                 
2360                 if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->val == KM_PRESS) {
2361                         int ret = WM_UI_HANDLER_BREAK;
2362                         /* XXX (a bit ugly) Special case handling for filebrowser drag button */
2363                         if (but->dragpoin && but->imb && ui_but_mouse_inside_icon(but, data->region, event)) {
2364                                 ret = WM_UI_HANDLER_CONTINUE;
2365                         }
2366                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2367                         return ret;
2368                 }
2369         }
2370         else if (data->state == BUTTON_STATE_WAIT_DRAG) {
2371                 
2372                 /* this function also ends state */
2373                 if (ui_but_start_drag(C, but, data, event)) {
2374                         return WM_UI_HANDLER_BREAK;
2375                 }
2376                 
2377                 /* If the mouse has been pressed and released, getting to 
2378                  * this point without triggering a drag, then clear the 
2379                  * drag state for this button and continue to pass on the event */
2380                 if (event->type == LEFTMOUSE && event->val == KM_RELEASE) {
2381                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2382                         return WM_UI_HANDLER_CONTINUE;
2383                 }
2384                 
2385                 /* while waiting for a drag to be triggered, always block 
2386                  * other events from getting handled */
2387                 return WM_UI_HANDLER_BREAK;
2388         }
2389         
2390         return WM_UI_HANDLER_CONTINUE;
2391 }
2392
2393 /* var names match ui_numedit_but_NUM */
2394 static float ui_numedit_apply_snapf(uiBut *but, float tempf, float softmin, float softmax, float softrange, int snap)
2395 {
2396         if (tempf == softmin || tempf == softmax || snap == 0) {
2397                 /* pass */
2398         }
2399         else {
2400                 float fac = 1.0f;
2401                 
2402                 if (ui_is_but_unit(but)) {
2403                         UnitSettings *unit = but->block->unit;
2404                         int unit_type = RNA_SUBTYPE_UNIT_VALUE(uiButGetUnitType(but));
2405
2406                         if (bUnit_IsValid(unit->system, unit_type)) {
2407                                 fac = (float)bUnit_BaseScalar(unit->system, unit_type);
2408                                 if (ELEM3(unit_type, B_UNIT_LENGTH, B_UNIT_AREA, B_UNIT_VOLUME)) {
2409                                         fac /= unit->scale_length;
2410                                 }
2411                         }
2412                 }
2413
2414                 if (fac != 1.0f) {
2415                         /* snap in unit-space */
2416                         tempf /= fac;
2417                         /* softmin /= fac; */ /* UNUSED */
2418                         /* softmax /= fac; */ /* UNUSED */
2419                         softrange /= fac;
2420                 }
2421
2422                 if (snap == 1) {
2423                         if      (softrange < 2.10f) tempf = 0.1f  * floorf(10.0f * tempf);
2424                         else if (softrange < 21.0f) tempf = floorf(tempf);
2425                         else                        tempf = 10.0f * floorf(tempf / 10.0f);
2426                 }
2427                 else if (snap == 2) {
2428                         if      (softrange < 2.10f) tempf = 0.01f * floorf(100.0f * tempf);
2429                         else if (softrange < 21.0f) tempf = 0.1f  * floorf(10.0f * tempf);
2430                         else                        tempf = floor(tempf);
2431                 }
2432                 
2433                 if (fac != 1.0f)
2434                         tempf *= fac;
2435         }
2436
2437         return tempf;
2438 }
2439
2440 static float ui_numedit_apply_snap(int temp, float softmin, float softmax, int snap)
2441 {
2442         if (temp == softmin || temp == softmax)
2443                 return temp;
2444
2445         switch (snap) {
2446                 case 0:
2447                         break;
2448                 case 1:
2449                         temp = 10 * (temp / 10);
2450                         break;
2451                 case 2:
2452                         temp = 100 * (temp / 100);
2453                         break;
2454         }
2455
2456         return temp;
2457 }
2458
2459 static int ui_numedit_but_NUM(uiBut *but, uiHandleButtonData *data, float fac, int snap, int mx)
2460 {
2461         float deler, tempf, softmin, softmax, softrange;
2462         int lvalue, temp, changed = 0;
2463         
2464         if (mx == data->draglastx)
2465                 return changed;
2466         
2467         /* drag-lock - prevent unwanted scroll adjustments */
2468         /* change value (now 3) to adjust threshold in pixels */
2469         if (data->draglock) {
2470                 if (abs(mx - data->dragstartx) <= 3)
2471                         return changed;
2472
2473                 data->draglock = 0;
2474                 data->dragstartx = mx;  /* ignore mouse movement within drag-lock */
2475         }
2476
2477         softmin = but->softmin;
2478         softmax = but->softmax;
2479         softrange = softmax - softmin;
2480
2481         if (ui_is_a_warp_but(but)) {
2482                 /* Mouse location isn't screen clamped to the screen so use a linear mapping
2483                  * 2px == 1-int, or 1px == 1-ClickStep */
2484                 if (ui_is_but_float(but)) {
2485                         fac *= 0.01f * but->a1;
2486                         tempf = (float)data->startvalue + ((float)(mx - data->dragstartx) * fac);
2487                         tempf = ui_numedit_apply_snapf(but, tempf, softmin, softmax, softrange, snap);
2488
2489 #if 1       /* fake moving the click start, nicer for dragging back after passing the limit */
2490                         if (tempf < softmin) {
2491                                 data->dragstartx -= (softmin - tempf) / fac;
2492                                 tempf = softmin;
2493                         }
2494                         else if (tempf > softmax) {
2495                                 data->dragstartx += (tempf - softmax) / fac;
2496                                 tempf = softmax;
2497                         }
2498 #else
2499                         CLAMP(tempf, softmin, softmax);
2500 #endif
2501
2502                         if (tempf != (float)data->value) {
2503                                 data->dragchange = 1;
2504                                 data->value = tempf;
2505                                 changed = 1;
2506                         }
2507                 }
2508                 else {
2509                         if      (softrange > 256) fac = 1.0;        /* 1px == 1 */
2510                         else if (softrange >  32) fac = 1.0 / 2.0;  /* 2px == 1 */
2511                         else                      fac = 1.0 / 16.0; /* 16px == 1? */
2512
2513                         temp = data->startvalue + (((double)mx - data->dragstartx) * (double)fac);
2514                         temp = ui_numedit_apply_snap(temp, softmin, softmax, snap);
2515
2516 #if 1       /* fake moving the click start, nicer for dragging back after passing the limit */
2517                         if (temp < softmin) {
2518                                 data->dragstartx -= (softmin - temp) / fac;
2519                                 temp = softmin;
2520                         }
2521                         else if (temp > softmax) {
2522                                 data->dragstartx += (temp - softmax) / fac;
2523                                 temp = softmax;
2524                         }
2525 #else
2526                         CLAMP(temp, softmin, softmax);
2527 #endif
2528
2529                         if (temp != data->value) {
2530                                 data->dragchange = 1;
2531                                 data->value = temp;
2532                                 changed = 1;
2533                         }
2534                 }
2535
2536                 data->draglastx = mx;
2537         }
2538         else {
2539                 /* Use a non-linear mapping of the mouse drag especially for large floats (normal behavior) */
2540                 deler = 500;
2541                 if (!ui_is_but_float(but)) {
2542                         /* prevent large ranges from getting too out of control */
2543                         if      (softrange > 600) deler = powf(softrange, 0.75);
2544                         else if (softrange < 100) deler = 200.0;
2545                         else if (softrange <  25) deler = 50.0;
2546                 }
2547                 deler /= fac;
2548
2549                 if (softrange > 11) {
2550                         /* non linear change in mouse input- good for high precicsion */
2551                         data->dragf += (((float)(mx - data->draglastx)) / deler) * (fabsf(data->dragstartx - mx) * 0.002f);
2552                 }
2553                 else if (softrange > 129) { /* only scale large int buttons */
2554                         /* non linear change in mouse input- good for high precicsionm ints need less fine tuning */
2555                         data->dragf += (((float)(mx - data->draglastx)) / deler) * (fabsf(data->dragstartx - mx) * 0.004f);
2556                 }
2557                 else {
2558                         /*no scaling */
2559                         data->dragf += ((float)(mx - data->draglastx)) / deler;
2560                 }
2561         
2562                 CLAMP(data->dragf, 0.0f, 1.0f);
2563                 data->draglastx = mx;
2564                 tempf = (softmin + data->dragf * softrange);
2565
2566
2567                 if (!ui_is_but_float(but)) {
2568                         temp = floorf(tempf + 0.5f);
2569
2570                         temp = ui_numedit_apply_snap(temp, softmin, softmax, snap);
2571
2572                         CLAMP(temp, softmin, softmax);
2573                         lvalue = (int)data->value;
2574                         
2575                         if (temp != lvalue) {
2576                                 data->dragchange = 1;
2577                                 data->value = (double)temp;
2578                                 changed = 1;
2579                         }
2580                 }
2581                 else {
2582                         temp = 0;
2583                         tempf = ui_numedit_apply_snapf(but, tempf, softmin, softmax, softrange, snap);
2584
2585                         CLAMP(tempf, softmin, softmax);
2586
2587                         if (tempf != (float)data->value) {
2588                                 data->dragchange = 1;
2589                                 data->value = tempf;
2590                                 changed = 1;
2591                         }
2592                 }
2593         }
2594
2595
2596         return changed;
2597 }
2598
2599 static int ui_do_but_NUM(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, wmEvent *event)
2600 {
2601         int mx, my; /* mouse location scaled to fit the UI */
2602         int screen_mx, screen_my; /* mouse location kept at screen pixel coords */
2603         int click = 0;
2604         int retval = WM_UI_HANDLER_CONTINUE;
2605         
2606         mx = screen_mx = event->x;
2607         my = screen_my = event->y;
2608
2609         ui_window_to_block(data->region, block, &mx, &my);
2610
2611         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2612                 /* XXX hardcoded keymap check.... */
2613                 if (event->type == WHEELDOWNMOUSE && event->alt) {
2614                         mx = but->rect.xmin;
2615                         click = 1;
2616                 }
2617                 else if (event->type == WHEELUPMOUSE && event->alt) {
2618                         mx = but->rect.xmax;
2619                         click = 1;
2620                 }
2621                 else if (event->val == KM_PRESS) {
2622                         if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->ctrl) {
2623                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2624                                 retval = WM_UI_HANDLER_BREAK;
2625                         }
2626                         else if (event->type == LEFTMOUSE) {
2627                                 data->dragstartx = data->draglastx = ui_is_a_warp_but(but) ? screen_mx : mx;
2628                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2629                                 retval = WM_UI_HANDLER_BREAK;
2630                         }
2631                         else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS) {
2632                                 click = 1;
2633                         }
2634                         else if (event->type == MINUSKEY && event->val == KM_PRESS) {
2635                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2636                                 data->value = -data->value;
2637                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2638                                 retval = WM_UI_HANDLER_BREAK;
2639                         }
2640                 }
2641                 
2642         }
2643         else if (data->state == BUTTON_STATE_NUM_EDITING) {
2644                 if (event->type == ESCKEY) {
2645                         data->cancel = TRUE;
2646                         data->escapecancel = TRUE;
2647                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2648                 }
2649                 else if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
2650                         if (data->dragchange)
2651                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2652                         else
2653                                 click = 1;
2654                 }
2655                 else if (event->type == MOUSEMOVE) {
2656                         float fac;
2657                         int snap;
2658
2659                         fac = 1.0f;
2660                         if (event->shift) fac /= 10.0f;
2661                         if (event->alt)   fac /= 20.0f;
2662                         
2663                         snap = (event->ctrl) ? (event->shift) ? 2 : 1 : 0;
2664
2665                         if (ui_numedit_but_NUM(but, data, fac, snap, (ui_is_a_warp_but(but) ? screen_mx : mx)))
2666                                 ui_numedit_apply(C, block, but, data);
2667                 }
2668                 retval = WM_UI_HANDLER_BREAK;
2669         }
2670         else if (data->state == BUTTON_STATE_TEXT_EDITING) {
2671                 ui_do_but_textedit(C, block, but, data, event);
2672                 retval = WM_UI_HANDLER_BREAK;
2673         }
2674         else if (data->state == BUTTON_STATE_TEXT_SELECTING) {
2675                 ui_do_but_textedit_select(C, block, but, data, event);
2676                 retval = WM_UI_HANDLER_BREAK;
2677         }
2678         
2679         if (click) {
2680                 /* we can click on the side arrows to increment/decrement,
2681                  * or click inside to edit the value directly */
2682                 float tempf, softmin, softmax;
2683                 int temp;
2684
2685                 softmin = but->softmin;
2686                 softmax = but->softmax;
2687
2688                 if (!ui_is_but_float(but)) {
2689                         if (mx < (but->rect.xmin + BLI_rctf_size_x(&but->rect) / 3 - 3)) {
2690                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2691
2692                                 temp = (int)data->value - 1;
2693                                 if (temp >= softmin && temp <= softmax)
2694                                         data->value = (double)temp;
2695                                 else
2696                                         data->cancel = TRUE;
2697
2698                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2699                         }
2700                         else if (mx > (but->rect.xmin + (2 * BLI_rctf_size_x(&but->rect) / 3) + 3)) {
2701                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2702
2703                                 temp = (int)data->value + 1;
2704                                 if (temp >= softmin && temp <= softmax)
2705                                         data->value = (double)temp;
2706                                 else
2707                                         data->cancel = TRUE;
2708
2709                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2710                         }
2711                         else {
2712                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2713                         }
2714                 }
2715                 else {
2716                         if (mx < (but->rect.xmin + BLI_rctf_size_x(&but->rect) / 3 - 3)) {
2717                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2718
2719                                 tempf = (float)data->value - 0.01f * but->a1;
2720                                 if (tempf < softmin) tempf = softmin;
2721                                 data->value = tempf;
2722
2723                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2724                         }
2725                         else if (mx > but->rect.xmin + (2 * (BLI_rctf_size_x(&but->rect) / 3) + 3)) {
2726                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2727
2728                                 tempf = (float)data->value + 0.01f * but->a1;
2729                                 if (tempf > softmax) tempf = softmax;
2730                                 data->value = tempf;
2731
2732                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2733                         }
2734                         else {
2735                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2736                         }
2737                 }
2738
2739                 retval = WM_UI_HANDLER_BREAK;
2740         }
2741         
2742         return retval;
2743 }
2744
2745 static int ui_numedit_but_SLI(uiBut *but, uiHandleButtonData *data, const short shift, const short ctrl, int mx)
2746 {
2747         float deler, f, tempf, softmin, softmax, softrange;
2748         int temp, lvalue, changed = 0;
2749
2750         softmin = but->softmin;
2751         softmax = but->softmax;
2752         softrange = softmax - softmin;
2753
2754         if (but->type == NUMSLI) {
2755                 deler = (BLI_rctf_size_x(&but->rect) - 5.0f * but->aspect);
2756         }
2757         else if (but->type == HSVSLI) {
2758                 deler = (BLI_rctf_size_x(&but->rect) / 2.0f - 5.0f * but->aspect);
2759         }
2760         else if (but->type == SCROLL) {
2761                 int horizontal = (BLI_rctf_size_x(&but->rect) > BLI_rctf_size_y(&but->rect));
2762                 float size = (horizontal) ? BLI_rctf_size_x(&but->rect) : -BLI_rctf_size_y(&but->rect);
2763                 deler = size * (but->softmax - but->softmin) / (but->softmax - but->softmin + but->a1);
2764         }
2765         else {
2766                 deler = (BLI_rctf_size_x(&but->rect) - 5.0f * but->aspect);
2767         }
2768
2769         f = (float)(mx - data->dragstartx) / deler + data->dragfstart;
2770         
2771         if (shift)
2772                 f = (f - data->dragfstart) / 10.0f + data->dragfstart;
2773
2774         CLAMP(f, 0.0f, 1.0f);
2775         tempf = softmin + f * softrange;
2776         temp = floorf(tempf + 0.5f);
2777
2778         if (ctrl) {
2779                 if (tempf == softmin || tempf == softmax) {
2780                         /* pass */
2781                 }
2782                 else if (ui_is_but_float(but)) {
2783
2784                         if (shift) {
2785                                 if      (tempf == softmin || tempf == softmax) {}
2786                                 else if (softmax - softmin < 2.10f) tempf = 0.01f * floorf(100.0f * tempf);
2787                                 else if (softmax - softmin < 21.0f) tempf = 0.1f  * floorf(10.0f * tempf);
2788                                 else                                tempf = floorf(tempf);
2789                         }
2790                         else {
2791                                 if      (softmax - softmin < 2.10f) tempf = 0.1f * floorf(10.0f * tempf);
2792                                 else if (softmax - softmin < 21.0f) tempf = floorf(tempf);
2793                                 else                                tempf = 10.0f * floorf(tempf / 10.0f);
2794                         }
2795                 }
2796                 else {
2797                         temp = 10 * (temp / 10);
2798                         tempf = temp;
2799                 }
2800         }
2801
2802         if (!ui_is_but_float(but)) {
2803                 lvalue = floor(data->value + 0.5);
2804
2805                 CLAMP(temp, softmin, softmax);
2806
2807                 if (temp != lvalue) {
2808                         data->value = temp;
2809                         data->dragchange = 1;
2810                         changed = 1;
2811                 }
2812         }
2813         else {
2814                 CLAMP(tempf, softmin, softmax);
2815
2816                 if (tempf != (float)data->value) {
2817                         data->value = tempf;
2818                         data->dragchange = 1;
2819                         changed = 1;
2820                 }
2821         }
2822
2823         return changed;
2824 }
2825
2826 static int ui_do_but_SLI(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, wmEvent *event)
2827 {
2828         int mx, my, click = 0;
2829         int retval = WM_UI_HANDLER_CONTINUE;
2830
2831         mx = event->x;
2832         my = event->y;
2833         ui_window_to_block(data->region, block, &mx, &my);
2834
2835         if (data->state == BUTTON_STATE_HIGHLIGHT) {
2836                 /* XXX hardcoded keymap check.... */
2837                 if (event->type == WHEELDOWNMOUSE && event->alt) {
2838                         mx = but->rect.xmin;
2839                         click = 2;
2840                 }
2841                 else if (event->type == WHEELUPMOUSE && event->alt) {
2842                         mx = but->rect.xmax;
2843                         click = 2;
2844                 }
2845                 else if (event->val == KM_PRESS) {
2846                         if (ELEM3(event->type, LEFTMOUSE, PADENTER, RETKEY) && event->ctrl) {
2847                                 button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2848                                 retval = WM_UI_HANDLER_BREAK;
2849                         }
2850                         /* alt-click on sides to get "arrows" like in NUM buttons, and match wheel usage above */
2851                         else if (event->type == LEFTMOUSE && event->alt) {
2852                                 int halfpos = BLI_rctf_cent_x(&but->rect);
2853                                 click = 2;
2854                                 if (mx < halfpos)
2855                                         mx = but->rect.xmin;
2856                                 else
2857                                         mx = but->rect.xmax;
2858                         }
2859                         else if (event->type == LEFTMOUSE) {
2860                                 data->dragstartx = mx;
2861                                 data->draglastx = mx;
2862                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2863                                 retval = WM_UI_HANDLER_BREAK;
2864                         }
2865                         else if (ELEM(event->type, PADENTER, RETKEY) && event->val == KM_PRESS) {
2866                                 click = 1;
2867                         }
2868                         else if (event->type == MINUSKEY && event->val == KM_PRESS) {
2869                                 button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2870                                 data->value = -data->value;
2871                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2872                                 retval = WM_UI_HANDLER_BREAK;
2873                         }
2874                 }
2875         }
2876         else if (data->state == BUTTON_STATE_NUM_EDITING) {
2877                 if (event->type == ESCKEY) {
2878                         data->cancel = TRUE;
2879                         data->escapecancel = TRUE;
2880                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2881                 }
2882                 else if (event->type == LEFTMOUSE && event->val != KM_PRESS) {
2883                         if (data->dragchange)
2884                                 button_activate_state(C, but, BUTTON_STATE_EXIT);
2885                         else
2886                                 click = 1;
2887                 }
2888                 else if (event->type == MOUSEMOVE) {
2889                         if (ui_numedit_but_SLI(but, data, event->shift, event->ctrl, mx))
2890                                 ui_numedit_apply(C, block, but, data);
2891                 }
2892                 retval = WM_UI_HANDLER_BREAK;
2893         }
2894         else if (data->state == BUTTON_STATE_TEXT_EDITING) {
2895                 ui_do_but_textedit(C, block, but, data, event);
2896                 retval = WM_UI_HANDLER_BREAK;
2897         }
2898         else if (data->state == BUTTON_STATE_TEXT_SELECTING) {
2899                 ui_do_but_textedit_select(C, block, but, data, event);
2900                 retval = WM_UI_HANDLER_BREAK;
2901         }
2902
2903         if (click) {
2904                 if (click == 2) {
2905                         /* nudge slider to the left or right */
2906                         float f, tempf, softmin, softmax, softrange;
2907                         int temp;
2908                         
2909                         button_activate_state(C, but, BUTTON_STATE_NUM_EDITING);
2910                         
2911                         softmin = but->softmin;
2912                         softmax = but->softmax;
2913                         softrange = softmax - softmin;
2914                         
2915                         tempf = data->value;
2916                         temp = (int)data->value;
2917
2918 #if 0
2919                         if (but->type == SLI) {
2920                                 f = (float)(mx - but->rect.xmin) / (BLI_rctf_size_x(&but->rect)); /* same as below */
2921                         }
2922                         else
2923 #endif
2924                         {
2925                                 f = (float)(mx - but->rect.xmin) / (BLI_rctf_size_x(&but->rect));
2926                         }
2927                         
2928                         f = softmin + f * softrange;
2929                         
2930                         if (!ui_is_but_float(but)) {
2931                                 if (f < temp) temp--;
2932                                 else temp++;
2933                                 
2934                                 if (temp >= softmin && temp <= softmax)
2935                                         data->value = temp;
2936                                 else
2937                                         data->cancel = TRUE;
2938                         } 
2939                         else {
2940                                 if (f < tempf) tempf -= 0.01f;
2941                                 else tempf += 0.01f;
2942                                 
2943                                 if (tempf >= softmin && tempf <= softmax)
2944                                         data->value = tempf;
2945                                 else
2946                                         data->cancel = TRUE;
2947                         }
2948                         
2949                         button_activate_state(C, but, BUTTON_STATE_EXIT);
2950                         retval = WM_UI_HANDLER_BREAK;
2951                 }
2952                 else {
2953                         /* edit the value directly */
2954                         button_activate_state(C, but, BUTTON_STATE_TEXT_EDITING);
2955                         retval = WM_UI_HANDLER_BREAK;
2956                 }
2957         }
2958         
2959         return retval;
2960 }
2961
2962 static int ui_do_but_SCROLL(bContext *C, uiBlock *block, uiBut *but, uiHandleButtonData *data, wmEvent *event)
2963 {
2964         int mx, my /*, click= 0 */;
2965         int retval = WM_UI_HANDLER_CONTINUE;