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