aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/generativeFill/GenerativeFill.tsx
blob: 1709962a227ea13c7e9807b9763af833f815d4e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
import './GenerativeFill.scss';
import React = require('react');
import { useEffect, useRef, useState } from 'react';
import { APISuccess, ImageUtility } from './generativeFillUtils/ImageHandler';
import { BrushHandler } from './generativeFillUtils/BrushHandler';
import { IconButton, TextField } from '@mui/material';
import { CursorData, Point } from './generativeFillUtils/generativeFillInterfaces';
import { activeColor, canvasSize, eraserColor, freeformRenderSize, offsetDistanceY, offsetX } from './generativeFillUtils/generativeFillConstants';
import { PointerHandler } from './generativeFillUtils/PointerHandler';
import { BsBrush, BsEraser, BsX } from 'react-icons/bs';
import { AiOutlineUpload } from 'react-icons/ai';
import { CiUndo, CiRedo } from 'react-icons/ci';
import Buttons from './GenerativeFillButtons';
import { EditableText } from 'browndash-components';
import { MainView } from '../../MainView';
import { Doc } from '../../../../fields/Doc';
import { Networking } from '../../../Network';
import { Utils } from '../../../../Utils';
import { DocUtils, Docs } from '../../../documents/Documents';
import { DocCast, NumCast } from '../../../../fields/Types';
import { CollectionDockingView } from '../../collections/CollectionDockingView';
import { OpenWhere, OpenWhereMod } from '../DocumentView';

/**
 * For images not 1024x1024 fill in the rest in solid black, or a
 * reflected version of the image.
 */

/**
 * TODO: Look into img onload, sometimes the canvas doesn't update properly
 */

enum BrushStyle {
    ADD,
    SUBTRACT,
    MARQUEE,
}

interface ImageEdit {
    imgElement: HTMLImageElement;
    parent: ImageEdit;
    children: ImageEdit[];
}

interface GenerativeFillProps {
    imageEditorOpen: boolean;
    imageEditorSource: string;
    imageRootDoc: Doc | undefined;
    addDoc: ((doc: Doc | Doc[], annotationKey?: string) => boolean) | undefined;
}

const GenerativeFill = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc }: GenerativeFillProps) => {
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const canvasBackgroundRef = useRef<HTMLCanvasElement>(null);
    const drawingAreaRef = useRef<HTMLDivElement>(null);
    const fileRef = useRef<HTMLInputElement>(null);
    const [cursorData, setCursorData] = useState<CursorData>({
        x: 0,
        y: 0,
        width: 150,
    });
    const [isBrushing, setIsBrushing] = useState(false);
    const [canvasScale, setCanvasScale] = useState(0.5);
    const [edits, setEdits] = useState<string[]>([]);
    const [brushStyle, setBrushStyle] = useState<BrushStyle>(BrushStyle.ADD);
    const [input, setInput] = useState('');
    const [loading, setLoading] = useState(false);
    // the current image in the main canvas
    const currImg = useRef<HTMLImageElement | null>(null);
    // the unedited version of each generation (parent)
    const originalImg = useRef<HTMLImageElement | null>(null);
    // stores history of data urls
    const undoStack = useRef<string[]>([]);
    // stores redo stack
    const redoStack = useRef<string[]>([]);

    // early stage properly, likely will get rid of
    const freeformPosition = useRef<number[]>([0, 0]);

    // which urls were already saved to canvas
    const savedSrcs = useRef<string[]>([]);

    // references to keep track of tree structure
    const newCollectionRef = useRef<Doc | null>(null);
    const parentDoc = useRef<Doc | null>(null);
    const childrenDocs = useRef<Doc[]>([]);

    // Undo and Redo
    const handleUndo = () => {
        const ctx = ImageUtility.getCanvasContext(canvasRef);
        if (!ctx || !currImg.current || !canvasRef.current) return;

        const target = undoStack.current[undoStack.current.length - 1];
        if (!target) {
            ImageUtility.drawImgToCanvas(currImg.current, canvasRef);
        } else {
            redoStack.current = [...redoStack.current, canvasRef.current.toDataURL()];
            const img = new Image();
            img.src = target;
            ImageUtility.drawImgToCanvas(img, canvasRef);
            undoStack.current = undoStack.current.slice(0, -1);
        }
    };

    const handleRedo = () => {
        // TODO: handle undo as well
        const target = redoStack.current[redoStack.current.length - 1];
        if (!target) {
        } else {
            const img = new Image();
            img.src = target;
            ImageUtility.drawImgToCanvas(img, canvasRef);
            redoStack.current = redoStack.current.slice(0, -1);
        }
    };

    const handleReset = () => {
        if (!canvasRef.current || !currImg.current) return;
        const ctx = ImageUtility.getCanvasContext(canvasRef);
        if (!ctx) return;
        ctx.clearRect(0, 0, canvasSize, canvasSize);
        undoStack.current = [];
        redoStack.current = [];
        ImageUtility.drawImgToCanvas(currImg.current, canvasRef, true);
    };

    // initiate brushing
    const handlePointerDown = (e: React.PointerEvent) => {
        const canvas = canvasRef.current;
        if (!canvas) return;
        const ctx = ImageUtility.getCanvasContext(canvasRef);
        if (!ctx) return;

        undoStack.current = [...undoStack.current, canvasRef.current.toDataURL()];
        redoStack.current = [];

        setIsBrushing(true);
        const { x, y } = PointerHandler.getPointRelativeToElement(canvas, e, canvasScale);

        BrushHandler.brushCircleOverlay(x, y, cursorData.width / 2 / canvasScale, ctx, eraserColor, brushStyle === BrushStyle.SUBTRACT);
    };

    // stop brushing, push to undo stack
    const handlePointerUp = (e: React.PointerEvent) => {
        const ctx = ImageUtility.getCanvasContext(canvasBackgroundRef);
        if (!ctx) return;
        if (!isBrushing) return;
        setIsBrushing(false);
    };

    // handles brushing on pointer movement
    useEffect(() => {
        if (!isBrushing) return;
        const canvas = canvasRef.current;
        if (!canvas) return;
        const ctx = ImageUtility.getCanvasContext(canvasRef);
        if (!ctx) return;

        const handlePointerMove = (e: PointerEvent) => {
            const currPoint = PointerHandler.getPointRelativeToElement(canvas, e, canvasScale);
            const lastPoint: Point = {
                x: currPoint.x - e.movementX / canvasScale,
                y: currPoint.y - e.movementY / canvasScale,
            };
            BrushHandler.createBrushPathOverlay(lastPoint, currPoint, cursorData.width / 2 / canvasScale, ctx, eraserColor, brushStyle === BrushStyle.SUBTRACT);
        };

        drawingAreaRef.current?.addEventListener('pointermove', handlePointerMove);
        return () => {
            drawingAreaRef.current?.removeEventListener('pointermove', handlePointerMove);
        };
    }, [isBrushing]);

    // first load
    useEffect(() => {
        console.log('first load');
        if (!imageEditorSource || imageEditorSource === '') return;
        const img = new Image();
        img.src = imageEditorSource;
        ImageUtility.drawImgToCanvas(img, canvasRef);
        currImg.current = img;
        originalImg.current = img;
        freeformPosition.current = [0, 0];

        return () => {
            console.log('cleanup');
            newCollectionRef.current = null;
            parentDoc.current = null;
            childrenDocs.current = [];
            currImg.current = null;
            originalImg.current = null;
            freeformPosition.current = [0, 0];
            undoStack.current = [];
            redoStack.current = [];
        };
    }, [canvasRef, imageEditorSource]);

    // handles brush sizing
    useEffect(() => {
        const handleKeyPress = (e: KeyboardEvent) => {
            if (e.key === 'ArrowUp') {
                e.preventDefault();
                e.stopPropagation();
                setCursorData(data => ({ ...data, width: data.width + 5 }));
            } else if (e.key === 'ArrowDown') {
                e.preventDefault();
                e.stopPropagation();
                setCursorData(data => (data.width >= 20 ? { ...data, width: data.width - 5 } : data));
            }
        };
        window.addEventListener('keydown', handleKeyPress);
        return () => window.removeEventListener('keydown', handleKeyPress);
    }, []);

    // handle pinch zoom
    useEffect(() => {
        const handlePinch = (e: WheelEvent) => {
            e.preventDefault();
            e.stopPropagation();
            const delta = e.deltaY;
            const scaleFactor = delta > 0 ? 0.98 : 1.02; // Adjust the scale factor as per your requirement
            setCanvasScale(prevScale => prevScale * scaleFactor);
        };

        drawingAreaRef.current?.addEventListener('wheel', handlePinch, {
            passive: false,
        });
        return () => drawingAreaRef.current?.removeEventListener('wheel', handlePinch);
    }, [drawingAreaRef]);

    // updates the current position of the cursor
    const updateCursorData = (e: React.PointerEvent) => {
        const drawingArea = drawingAreaRef.current;
        if (!drawingArea) return;
        const { x, y } = PointerHandler.getPointRelativeToElement(drawingArea, e, 1);
        setCursorData(data => ({
            ...data,
            x,
            y,
        }));
    };

    // File upload
    const uploadImg = (e: React.ChangeEvent<HTMLInputElement>) => {
        if (e.target.files) {
            const file = e.target.files[0];
            const image = new Image();
            const imgUrl = URL.createObjectURL(file);
            image.src = imgUrl;
            ImageUtility.drawImgToCanvas(image, canvasRef);
            currImg.current = image;
        }
    };

    // Get AI Edit
    const getEdit = async () => {
        const img = currImg.current;
        if (!img) return;
        const canvas = canvasRef.current;
        if (!canvas) return;
        const ctx = ImageUtility.getCanvasContext(canvasRef);
        if (!ctx) return;
        setLoading(true);
        // need to adjust later
        try {
            const maskBlob = await ImageUtility.canvasToBlob(canvas);
            const imgBlob = await ImageUtility.canvasToBlob(ImageUtility.getCanvasImg(img));
            const res = await ImageUtility.getEdit(imgBlob, maskBlob, input !== '' ? input + ' in the same style' : 'Fill in the image in the same style', 2);
            // const res = await ImageUtility.mockGetEdit(img.src);

            // create first image
            if (!newCollectionRef.current) {
                if (!(originalImg.current && imageRootDoc)) return;
                console.log('creating first image');
                // create new collection and add it to the view
                newCollectionRef.current = Docs.Create.FreeformDocument([], { x: NumCast(imageRootDoc.x) + NumCast(imageRootDoc._width) + 20, y: NumCast(imageRootDoc.y), _width: 1000, _height: 1000 });
                DocUtils.MakeLink(imageRootDoc, newCollectionRef.current, { link_relationship: 'Image Edit Version History', link_displayLine: false });
                addDoc?.(newCollectionRef.current);
                await createNewImgDoc(originalImg.current, true);
            } else {
                parentDoc.current = childrenDocs.current[childrenDocs.current.length - 1];
                childrenDocs.current = [];
            }

            originalImg.current = currImg.current;

            const { urls } = res as APISuccess;
            const image = new Image();
            image.src = urls[0];
            setEdits(urls);
            ImageUtility.drawImgToCanvas(image, canvasRef);
            currImg.current = image;
            onSave();
            freeformPosition.current[0] += 1;
            freeformPosition.current[1] = 0;
        } catch (err) {
            console.log(err);
        }
        setLoading(false);
    };

    // adjusts all the img positions to be aligned
    const adjustImgPositions = () => {
        if (!parentDoc.current) return;
        const startY = NumCast(parentDoc.current.y);
        const len = childrenDocs.current.length;
        console.log(len);
        let initialYPositions: number[] = [];
        for (let i = 0; i < len; i++) {
            initialYPositions.push(startY + i * offsetDistanceY);
        }
        childrenDocs.current.forEach((doc, i) => {
            if (len % 2 === 1) {
                doc.y = initialYPositions[i] - Math.floor(len / 2) * offsetDistanceY;
            } else {
                doc.y = initialYPositions[i] - (len / 2 - 1 / 2) * offsetDistanceY;
            }
        });
    };

    // creates a new image document and returns its reference
    const createNewImgDoc = async (img: HTMLImageElement, firstDoc: boolean): Promise<Doc | undefined> => {
        if (!newCollectionRef.current || !imageRootDoc) return;
        const src = img.src;
        const [result] = await Networking.PostToServer('/uploadRemoteImage', { sources: [src] });
        const source = Utils.prepend(result.accessPaths.agnostic.client);

        if (firstDoc) {
            const x = 0;
            const initialY = 500;
            console.log('first doc');

            const newImg = Docs.Create.ImageDocument(source, {
                x: x,
                y: initialY,
                _height: freeformRenderSize,
                _width: freeformRenderSize,
                data_nativeWidth: result.nativeWidth,
                data_nativeHeight: result.nativeHeight,
            });

            Doc.AddDocToList(newCollectionRef.current, undefined, newImg);
            parentDoc.current = newImg;
            return newImg;
        } else {
            if (!parentDoc.current) return;
            const x = NumCast(parentDoc.current.x) + freeformRenderSize + offsetX;
            // dummy position
            console.log('creating child elements');
            const initialY = 0;

            const newImg = Docs.Create.ImageDocument(source, {
                x: x,
                y: initialY,
                _height: freeformRenderSize,
                _width: freeformRenderSize,
                data_nativeWidth: result.nativeWidth,
                data_nativeHeight: result.nativeHeight,
            });

            childrenDocs.current.push(newImg);
            DocUtils.MakeLink(parentDoc.current, newImg, { link_relationship: 'Image Edit', link_displayLine: true });
            adjustImgPositions();

            Doc.AddDocToList(newCollectionRef.current, undefined, newImg);
            return newImg;
        }
    };

    // need to maybe call on every img click, not just when the save btn is clicked
    const onSave = async () => {
        setLoading(true);
        if (!currImg.current || !originalImg.current || !imageRootDoc) return;
        try {
            // if (!newCollectionRef.current) {
            //     console.log('creating first image');
            //     // create new collection and add it to the view
            //     newCollectionRef.current = Docs.Create.FreeformDocument([], { x: NumCast(imageRootDoc.x) + NumCast(imageRootDoc._width) + 20, y: NumCast(imageRootDoc.y), _width: 1000, _height: 1000 });
            //     addDoc?.(newCollectionRef.current);
            //     await createNewImgDoc(originalImg.current, true);
            // }
            console.log('creating another image');
            await createNewImgDoc(currImg.current, false);
            // CollectionDockingView.AddSplit(Doc.MakeCopy(DocCast(Doc.UserDoc().emptyPane)), OpenWhereMod.right);
            // CollectionDockingView.AddSplit(newCollection,OpenWhere.inParent)
            // mind mapping
            // this.props.addDocTab();
        } catch (err) {
            console.log(err);
        }
        setLoading(false);
    };

    const handleViewClose = () => {
        // if (newCollectionRef.current) {
        //     CollectionDockingView.AddSplit(newCollectionRef.current, OpenWhereMod.right);
        // }
        MainView.Instance.setImageEditorOpen(false);
        MainView.Instance.setImageEditorSource('');
        setEdits([]);
    };

    return (
        <div className="generativeFillContainer" style={{ display: imageEditorOpen ? 'flex' : 'none' }}>
            <div className="generativeFillControls">
                <h1>Generative Fill</h1>
                <div style={{ display: 'flex', alignItems: 'center', gap: '1.5rem' }}>
                    <Buttons canvasRef={canvasRef} currImg={currImg} getEdit={getEdit} loading={loading} onSave={onSave} onReset={handleReset} />
                    <IconButton onClick={handleViewClose}>
                        <BsX color={activeColor} />
                    </IconButton>
                </div>
            </div>
            {/* Main canvas for editing */}
            <div
                className="drawingArea" // this only works if pointerevents: none is set on the custom pointer
                ref={drawingAreaRef}
                onPointerOver={updateCursorData}
                onPointerMove={updateCursorData}
                onPointerDown={handlePointerDown}
                onPointerUp={handlePointerUp}>
                <canvas ref={canvasRef} width={canvasSize} height={canvasSize} style={{ transform: `scale(${canvasScale})` }} />
                <canvas ref={canvasBackgroundRef} width={canvasSize} height={canvasSize} style={{ transform: `scale(${canvasScale})` }} />
                <div
                    className="pointer"
                    style={{
                        left: cursorData.x,
                        top: cursorData.y,
                        width: cursorData.width,
                        height: cursorData.width,
                    }}>
                    <div className="innerPointer"></div>
                </div>
                {/* Icons */}
                <div className="iconContainer">
                    <input ref={fileRef} type="file" accept="image/*" onChange={uploadImg} style={{ display: 'none' }} />
                    <IconButton
                        onClick={() => {
                            if (fileRef.current) {
                                fileRef.current.click();
                            }
                        }}>
                        <AiOutlineUpload />
                    </IconButton>
                    <IconButton
                        onClick={() => {
                            setBrushStyle(BrushStyle.ADD);
                        }}>
                        <BsBrush color={brushStyle === BrushStyle.ADD ? activeColor : 'inherit'} />
                    </IconButton>
                    {/* Undo and Redo */}
                    <IconButton
                        onPointerDown={e => {
                            e.stopPropagation();
                            handleUndo();
                        }}
                        onPointerUp={e => {
                            e.stopPropagation();
                        }}>
                        <CiUndo />
                    </IconButton>
                    <IconButton
                        onPointerDown={e => {
                            e.stopPropagation();
                            handleRedo();
                        }}
                        onPointerUp={e => {
                            e.stopPropagation();
                        }}>
                        <CiRedo />
                    </IconButton>
                </div>
                {/* Edits thumbnails*/}
                <div className="editsBox">
                    {edits.map((edit, i) => (
                        <img
                            key={i}
                            width={100}
                            height={100}
                            src={edit}
                            onClick={() => {
                                const img = new Image();
                                img.src = edit;
                                ImageUtility.drawImgToCanvas(img, canvasRef);
                                currImg.current = img;
                                onSave();
                            }}
                        />
                    ))}
                    {/* Original img thumbnail */}
                    {edits.length > 0 && (
                        <div style={{ position: 'relative' }}>
                            <label
                                style={{
                                    position: 'absolute',
                                    bottom: 10,
                                    left: 10,
                                    color: '#ffffff',
                                    fontSize: '0.8rem',
                                    letterSpacing: '1px',
                                    textTransform: 'uppercase',
                                }}>
                                Original
                            </label>
                            <img
                                width={100}
                                height={100}
                                src={originalImg.current?.src}
                                style={{ cursor: 'pointer' }}
                                onClick={() => {
                                    if (!originalImg.current) return;
                                    const img = new Image();
                                    img.src = originalImg.current.src;
                                    ImageUtility.drawImgToCanvas(img, canvasRef);
                                    currImg.current = img;
                                }}
                            />
                        </div>
                    )}
                </div>
            </div>
            <div>
                <TextField
                    value={input}
                    onChange={e => setInput(e.target.value)}
                    disabled={isBrushing}
                    type="text"
                    label="Prompt"
                    placeholder="Prompt..."
                    InputLabelProps={{ style: { fontSize: '1.5rem' } }}
                    inputProps={{ style: { fontSize: '1.5rem' } }}
                    sx={{
                        backgroundColor: '#ffffff',
                        position: 'absolute',
                        bottom: '1rem',
                        transform: 'translateX(calc(50vw - 50%))',
                        width: 'calc(100vw - 4rem)',
                        scale: 1.2,
                    }}
                />
            </div>
        </div>
    );
};

export default GenerativeFill;