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