FlatCAMEditor.py 248 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. ############################################################ #
  9. # File Modified: Marius Adrian Stanciu (c) #
  10. # Date: 3/10/2019 #
  11. ############################################################
  12. from PyQt5 import QtGui, QtCore, QtWidgets
  13. from PyQt5.QtCore import Qt, QSettings
  14. import FlatCAMApp
  15. from camlib import *
  16. from FlatCAMTool import FlatCAMTool
  17. from ObjectUI import LengthEntry, RadioSet
  18. from shapely.geometry import Polygon, LineString, Point, LinearRing, MultiLineString
  19. from shapely.geometry import MultiPoint, MultiPolygon
  20. from shapely.geometry import box as shply_box
  21. from shapely.ops import cascaded_union, unary_union
  22. import shapely.affinity as affinity
  23. from shapely.wkt import loads as sloads
  24. from shapely.wkt import dumps as sdumps
  25. from shapely.geometry.base import BaseGeometry
  26. from numpy import arctan2, Inf, array, sqrt, pi, ceil, sin, cos, sign, dot
  27. from numpy.linalg import solve
  28. from rtree import index as rtindex
  29. from GUIElements import OptionalInputSection, FCCheckBox, FCEntry, FCEntry2, FCComboBox, FCTextAreaRich, \
  30. VerticalScrollArea, FCTable, FCDoubleSpinner, FCButton, EvalEntry2, FCInputDialog
  31. from ParseFont import *
  32. from vispy.scene.visuals import Markers
  33. from copy import copy
  34. import freetype as ft
  35. import gettext
  36. import FlatCAMTranslation as fcTranslate
  37. fcTranslate.apply_language('FlatCAMEditor')
  38. import builtins
  39. if '_' not in builtins.__dict__:
  40. _ = gettext.gettext
  41. class BufferSelectionTool(FlatCAMTool):
  42. """
  43. Simple input for buffer distance.
  44. """
  45. toolName = "Buffer Selection"
  46. def __init__(self, app, draw_app):
  47. FlatCAMTool.__init__(self, app)
  48. self.draw_app = draw_app
  49. # Title
  50. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  51. title_label.setStyleSheet("""
  52. QLabel
  53. {
  54. font-size: 16px;
  55. font-weight: bold;
  56. }
  57. """)
  58. self.layout.addWidget(title_label)
  59. # this way I can hide/show the frame
  60. self.buffer_tool_frame = QtWidgets.QFrame()
  61. self.buffer_tool_frame.setContentsMargins(0, 0, 0, 0)
  62. self.layout.addWidget(self.buffer_tool_frame)
  63. self.buffer_tools_box = QtWidgets.QVBoxLayout()
  64. self.buffer_tools_box.setContentsMargins(0, 0, 0, 0)
  65. self.buffer_tool_frame.setLayout(self.buffer_tools_box)
  66. # Form Layout
  67. form_layout = QtWidgets.QFormLayout()
  68. self.buffer_tools_box.addLayout(form_layout)
  69. # Buffer distance
  70. self.buffer_distance_entry = FCEntry()
  71. form_layout.addRow(_("Buffer distance:"), self.buffer_distance_entry)
  72. self.buffer_corner_lbl = QtWidgets.QLabel(_("Buffer corner:"))
  73. self.buffer_corner_lbl.setToolTip(
  74. _("There are 3 types of corners:\n"
  75. " - 'Round': the corner is rounded for exterior buffer.\n"
  76. " - 'Square:' the corner is met in a sharp angle for exterior buffer.\n"
  77. " - 'Beveled:' the corner is a line that directly connects the features meeting in the corner")
  78. )
  79. self.buffer_corner_cb = FCComboBox()
  80. self.buffer_corner_cb.addItem(_("Round"))
  81. self.buffer_corner_cb.addItem(_("Square"))
  82. self.buffer_corner_cb.addItem(_("Beveled"))
  83. form_layout.addRow(self.buffer_corner_lbl, self.buffer_corner_cb)
  84. # Buttons
  85. hlay = QtWidgets.QHBoxLayout()
  86. self.buffer_tools_box.addLayout(hlay)
  87. self.buffer_int_button = QtWidgets.QPushButton(_("Buffer Interior"))
  88. hlay.addWidget(self.buffer_int_button)
  89. self.buffer_ext_button = QtWidgets.QPushButton(_("Buffer Exterior"))
  90. hlay.addWidget(self.buffer_ext_button)
  91. hlay1 = QtWidgets.QHBoxLayout()
  92. self.buffer_tools_box.addLayout(hlay1)
  93. self.buffer_button = QtWidgets.QPushButton(_("Full Buffer"))
  94. hlay1.addWidget(self.buffer_button)
  95. self.layout.addStretch()
  96. # Signals
  97. self.buffer_button.clicked.connect(self.on_buffer)
  98. self.buffer_int_button.clicked.connect(self.on_buffer_int)
  99. self.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  100. # Init GUI
  101. self.buffer_distance_entry.set_value(0.01)
  102. def run(self):
  103. self.app.report_usage("Geo Editor ToolBuffer()")
  104. FlatCAMTool.run(self)
  105. # if the splitter us hidden, display it
  106. if self.app.ui.splitter.sizes()[0] == 0:
  107. self.app.ui.splitter.setSizes([1, 1])
  108. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  109. def on_buffer(self):
  110. try:
  111. buffer_distance = float(self.buffer_distance_entry.get_value())
  112. except ValueError:
  113. # try to convert comma to decimal point. if it's still not working error message and return
  114. try:
  115. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  116. self.buffer_distance_entry.set_value(buffer_distance)
  117. except ValueError:
  118. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  119. "Add it and retry."))
  120. return
  121. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  122. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  123. join_style = self.buffer_corner_cb.currentIndex() + 1
  124. self.draw_app.buffer(buffer_distance, join_style)
  125. def on_buffer_int(self):
  126. try:
  127. buffer_distance = float(self.buffer_distance_entry.get_value())
  128. except ValueError:
  129. # try to convert comma to decimal point. if it's still not working error message and return
  130. try:
  131. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  132. self.buffer_distance_entry.set_value(buffer_distance)
  133. except ValueError:
  134. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  135. "Add it and retry."))
  136. return
  137. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  138. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  139. join_style = self.buffer_corner_cb.currentIndex() + 1
  140. self.draw_app.buffer_int(buffer_distance, join_style)
  141. def on_buffer_ext(self):
  142. try:
  143. buffer_distance = float(self.buffer_distance_entry.get_value())
  144. except ValueError:
  145. # try to convert comma to decimal point. if it's still not working error message and return
  146. try:
  147. buffer_distance = float(self.buffer_distance_entry.get_value().replace(',', '.'))
  148. self.buffer_distance_entry.set_value(buffer_distance)
  149. except ValueError:
  150. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  151. "Add it and retry."))
  152. return
  153. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  154. # I populated the combobox such that the index coincide with the join styles value (which is really an INT)
  155. join_style = self.buffer_corner_cb.currentIndex() + 1
  156. self.draw_app.buffer_ext(buffer_distance, join_style)
  157. def hide_tool(self):
  158. self.buffer_tool_frame.hide()
  159. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  160. class TextInputTool(FlatCAMTool):
  161. """
  162. Simple input for buffer distance.
  163. """
  164. toolName = "Text Input Tool"
  165. def __init__(self, app):
  166. FlatCAMTool.__init__(self, app)
  167. self.app = app
  168. self.text_path = []
  169. self.f_parse = ParseFont(self)
  170. self.f_parse.get_fonts_by_types()
  171. # this way I can hide/show the frame
  172. self.text_tool_frame = QtWidgets.QFrame()
  173. self.text_tool_frame.setContentsMargins(0, 0, 0, 0)
  174. self.layout.addWidget(self.text_tool_frame)
  175. self.text_tools_box = QtWidgets.QVBoxLayout()
  176. self.text_tools_box.setContentsMargins(0, 0, 0, 0)
  177. self.text_tool_frame.setLayout(self.text_tools_box)
  178. # Title
  179. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  180. title_label.setStyleSheet("""
  181. QLabel
  182. {
  183. font-size: 16px;
  184. font-weight: bold;
  185. }
  186. """)
  187. self.text_tools_box.addWidget(title_label)
  188. # Form Layout
  189. self.form_layout = QtWidgets.QFormLayout()
  190. self.text_tools_box.addLayout(self.form_layout)
  191. # Font type
  192. if sys.platform == "win32":
  193. f_current = QtGui.QFont("Arial")
  194. elif sys.platform == "linux":
  195. f_current = QtGui.QFont("FreeMono")
  196. else:
  197. f_current = QtGui.QFont("Helvetica Neue")
  198. self.font_name = f_current.family()
  199. self.font_type_cb = QtWidgets.QFontComboBox(self)
  200. self.font_type_cb.setCurrentFont(f_current)
  201. self.form_layout.addRow("Font:", self.font_type_cb)
  202. # Flag variables to show if font is bold, italic, both or none (regular)
  203. self.font_bold = False
  204. self.font_italic = False
  205. # # Create dictionaries with the filenames of the fonts
  206. # # Key: Fontname
  207. # # Value: Font File Name.ttf
  208. #
  209. # # regular fonts
  210. # self.ff_names_regular ={}
  211. # # bold fonts
  212. # self.ff_names_bold = {}
  213. # # italic fonts
  214. # self.ff_names_italic = {}
  215. # # bold and italic fonts
  216. # self.ff_names_bi = {}
  217. #
  218. # if sys.platform == 'win32':
  219. # from winreg import ConnectRegistry, OpenKey, EnumValue, HKEY_LOCAL_MACHINE
  220. # registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
  221. # font_key = OpenKey(registry, "SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts")
  222. # try:
  223. # i = 0
  224. # while 1:
  225. # name_font, value, type = EnumValue(font_key, i)
  226. # k = name_font.replace(" (TrueType)", '')
  227. # if 'Bold' in k and 'Italic' in k:
  228. # k = k.replace(" Bold Italic", '')
  229. # self.ff_names_bi.update({k: value})
  230. # elif 'Bold' in k:
  231. # k = k.replace(" Bold", '')
  232. # self.ff_names_bold.update({k: value})
  233. # elif 'Italic' in k:
  234. # k = k.replace(" Italic", '')
  235. # self.ff_names_italic.update({k: value})
  236. # else:
  237. # self.ff_names_regular.update({k: value})
  238. # i += 1
  239. # except WindowsError:
  240. # pass
  241. # Font size
  242. self.font_size_cb = FCComboBox()
  243. self.font_size_cb.setEditable(True)
  244. self.font_size_cb.setMinimumContentsLength(3)
  245. self.font_size_cb.setMaximumWidth(70)
  246. font_sizes = ['6', '7', '8', '9', '10', '11', '12', '13', '14',
  247. '15', '16', '18', '20', '22', '24', '26', '28',
  248. '32', '36', '40', '44', '48', '54', '60', '66',
  249. '72', '80', '88', '96']
  250. for i in font_sizes:
  251. self.font_size_cb.addItem(i)
  252. self.font_size_cb.setCurrentIndex(4)
  253. hlay = QtWidgets.QHBoxLayout()
  254. hlay.addWidget(self.font_size_cb)
  255. hlay.addStretch()
  256. self.font_bold_tb = QtWidgets.QToolButton()
  257. self.font_bold_tb.setCheckable(True)
  258. self.font_bold_tb.setIcon(QtGui.QIcon('share/bold32.png'))
  259. hlay.addWidget(self.font_bold_tb)
  260. self.font_italic_tb = QtWidgets.QToolButton()
  261. self.font_italic_tb.setCheckable(True)
  262. self.font_italic_tb.setIcon(QtGui.QIcon('share/italic32.png'))
  263. hlay.addWidget(self.font_italic_tb)
  264. self.form_layout.addRow("Size:", hlay)
  265. # Text input
  266. self.text_input_entry = FCTextAreaRich()
  267. self.text_input_entry.setTabStopWidth(12)
  268. self.text_input_entry.setMinimumHeight(200)
  269. # self.text_input_entry.setMaximumHeight(150)
  270. self.text_input_entry.setCurrentFont(f_current)
  271. self.text_input_entry.setFontPointSize(10)
  272. self.form_layout.addRow("Text:", self.text_input_entry)
  273. # Buttons
  274. hlay1 = QtWidgets.QHBoxLayout()
  275. self.form_layout.addRow("", hlay1)
  276. hlay1.addStretch()
  277. self.apply_button = QtWidgets.QPushButton("Apply")
  278. hlay1.addWidget(self.apply_button)
  279. # self.layout.addStretch()
  280. # Signals
  281. self.apply_button.clicked.connect(self.on_apply_button)
  282. self.font_type_cb.currentFontChanged.connect(self.font_family)
  283. self.font_size_cb.activated.connect(self.font_size)
  284. self.font_bold_tb.clicked.connect(self.on_bold_button)
  285. self.font_italic_tb.clicked.connect(self.on_italic_button)
  286. def on_apply_button(self):
  287. font_to_geo_type = ""
  288. if self.font_bold is True:
  289. font_to_geo_type = 'bold'
  290. elif self.font_italic is True:
  291. font_to_geo_type = 'italic'
  292. elif self.font_bold is True and self.font_italic is True:
  293. font_to_geo_type = 'bi'
  294. elif self.font_bold is False and self.font_italic is False:
  295. font_to_geo_type = 'regular'
  296. string_to_geo = self.text_input_entry.get_value()
  297. font_to_geo_size = self.font_size_cb.get_value()
  298. self.text_path = self.f_parse.font_to_geometry(
  299. char_string=string_to_geo,
  300. font_name=self.font_name,
  301. font_size=font_to_geo_size,
  302. font_type=font_to_geo_type,
  303. units=self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper())
  304. def font_family(self, font):
  305. self.text_input_entry.selectAll()
  306. font.setPointSize(float(self.font_size_cb.get_value()))
  307. self.text_input_entry.setCurrentFont(font)
  308. self.font_name = self.font_type_cb.currentFont().family()
  309. def font_size(self):
  310. self.text_input_entry.selectAll()
  311. self.text_input_entry.setFontPointSize(float(self.font_size_cb.get_value()))
  312. def on_bold_button(self):
  313. if self.font_bold_tb.isChecked():
  314. self.text_input_entry.selectAll()
  315. self.text_input_entry.setFontWeight(QtGui.QFont.Bold)
  316. self.font_bold = True
  317. else:
  318. self.text_input_entry.selectAll()
  319. self.text_input_entry.setFontWeight(QtGui.QFont.Normal)
  320. self.font_bold = False
  321. def on_italic_button(self):
  322. if self.font_italic_tb.isChecked():
  323. self.text_input_entry.selectAll()
  324. self.text_input_entry.setFontItalic(True)
  325. self.font_italic = True
  326. else:
  327. self.text_input_entry.selectAll()
  328. self.text_input_entry.setFontItalic(False)
  329. self.font_italic = False
  330. def hide_tool(self):
  331. self.text_tool_frame.hide()
  332. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  333. class PaintOptionsTool(FlatCAMTool):
  334. """
  335. Inputs to specify how to paint the selected polygons.
  336. """
  337. toolName = "Paint Tool"
  338. def __init__(self, app, fcdraw):
  339. FlatCAMTool.__init__(self, app)
  340. self.app = app
  341. self.fcdraw = fcdraw
  342. ## Title
  343. title_label = QtWidgets.QLabel("%s" % ('Editor ' + self.toolName))
  344. title_label.setStyleSheet("""
  345. QLabel
  346. {
  347. font-size: 16px;
  348. font-weight: bold;
  349. }
  350. """)
  351. self.layout.addWidget(title_label)
  352. grid = QtWidgets.QGridLayout()
  353. self.layout.addLayout(grid)
  354. # Tool dia
  355. ptdlabel = QtWidgets.QLabel(_('Tool dia:'))
  356. ptdlabel.setToolTip(
  357. _( "Diameter of the tool to\n"
  358. "be used in the operation.")
  359. )
  360. grid.addWidget(ptdlabel, 0, 0)
  361. self.painttooldia_entry = FCEntry()
  362. grid.addWidget(self.painttooldia_entry, 0, 1)
  363. # Overlap
  364. ovlabel = QtWidgets.QLabel(_('Overlap:'))
  365. ovlabel.setToolTip(
  366. _("How much (fraction) of the tool width to overlap each tool pass.\n"
  367. "Example:\n"
  368. "A value here of 0.25 means 25% from the tool diameter found above.\n\n"
  369. "Adjust the value starting with lower values\n"
  370. "and increasing it if areas that should be painted are still \n"
  371. "not painted.\n"
  372. "Lower values = faster processing, faster execution on PCB.\n"
  373. "Higher values = slow processing and slow execution on CNC\n"
  374. "due of too many paths.")
  375. )
  376. grid.addWidget(ovlabel, 1, 0)
  377. self.paintoverlap_entry = FCEntry()
  378. self.paintoverlap_entry.setValidator(QtGui.QDoubleValidator(0.0000, 1.0000, 4))
  379. grid.addWidget(self.paintoverlap_entry, 1, 1)
  380. # Margin
  381. marginlabel = QtWidgets.QLabel(_('Margin:'))
  382. marginlabel.setToolTip(
  383. _( "Distance by which to avoid\n"
  384. "the edges of the polygon to\n"
  385. "be painted.")
  386. )
  387. grid.addWidget(marginlabel, 2, 0)
  388. self.paintmargin_entry = FCEntry()
  389. grid.addWidget(self.paintmargin_entry, 2, 1)
  390. # Method
  391. methodlabel = QtWidgets.QLabel(_('Method:'))
  392. methodlabel.setToolTip(
  393. _("Algorithm to paint the polygon:<BR>"
  394. "<B>Standard</B>: Fixed step inwards.<BR>"
  395. "<B>Seed-based</B>: Outwards from seed.")
  396. )
  397. grid.addWidget(methodlabel, 3, 0)
  398. self.paintmethod_combo = RadioSet([
  399. {"label": _("Standard"), "value": "standard"},
  400. {"label": _("Seed-based"), "value": "seed"},
  401. {"label": _("Straight lines"), "value": "lines"}
  402. ], orientation='vertical', stretch=False)
  403. grid.addWidget(self.paintmethod_combo, 3, 1)
  404. # Connect lines
  405. pathconnectlabel = QtWidgets.QLabel(_("Connect:"))
  406. pathconnectlabel.setToolTip(
  407. _( "Draw lines between resulting\n"
  408. "segments to minimize tool lifts.")
  409. )
  410. grid.addWidget(pathconnectlabel, 4, 0)
  411. self.pathconnect_cb = FCCheckBox()
  412. grid.addWidget(self.pathconnect_cb, 4, 1)
  413. contourlabel = QtWidgets.QLabel(_("Contour:"))
  414. contourlabel.setToolTip(
  415. _("Cut around the perimeter of the polygon\n"
  416. "to trim rough edges.")
  417. )
  418. grid.addWidget(contourlabel, 5, 0)
  419. self.paintcontour_cb = FCCheckBox()
  420. grid.addWidget(self.paintcontour_cb, 5, 1)
  421. ## Buttons
  422. hlay = QtWidgets.QHBoxLayout()
  423. self.layout.addLayout(hlay)
  424. hlay.addStretch()
  425. self.paint_button = QtWidgets.QPushButton(_("Paint"))
  426. hlay.addWidget(self.paint_button)
  427. self.layout.addStretch()
  428. ## Signals
  429. self.paint_button.clicked.connect(self.on_paint)
  430. self.set_tool_ui()
  431. def run(self):
  432. self.app.report_usage("Geo Editor ToolPaint()")
  433. FlatCAMTool.run(self)
  434. # if the splitter us hidden, display it
  435. if self.app.ui.splitter.sizes()[0] == 0:
  436. self.app.ui.splitter.setSizes([1, 1])
  437. self.app.ui.notebook.setTabText(2, _("Paint Tool"))
  438. def set_tool_ui(self):
  439. ## Init GUI
  440. if self.app.defaults["tools_painttooldia"]:
  441. self.painttooldia_entry.set_value(self.app.defaults["tools_painttooldia"])
  442. else:
  443. self.painttooldia_entry.set_value(0.0)
  444. if self.app.defaults["tools_paintoverlap"]:
  445. self.paintoverlap_entry.set_value(self.app.defaults["tools_paintoverlap"])
  446. else:
  447. self.paintoverlap_entry.set_value(0.0)
  448. if self.app.defaults["tools_paintmargin"]:
  449. self.paintmargin_entry.set_value(self.app.defaults["tools_paintmargin"])
  450. else:
  451. self.paintmargin_entry.set_value(0.0)
  452. if self.app.defaults["tools_paintmethod"]:
  453. self.paintmethod_combo.set_value(self.app.defaults["tools_paintmethod"])
  454. else:
  455. self.paintmethod_combo.set_value("seed")
  456. if self.app.defaults["tools_pathconnect"]:
  457. self.pathconnect_cb.set_value(self.app.defaults["tools_pathconnect"])
  458. else:
  459. self.pathconnect_cb.set_value(False)
  460. if self.app.defaults["tools_paintcontour"]:
  461. self.paintcontour_cb.set_value(self.app.defaults["tools_paintcontour"])
  462. else:
  463. self.paintcontour_cb.set_value(False)
  464. def on_paint(self):
  465. if not self.fcdraw.selected:
  466. self.app.inform.emit(_("[WARNING_NOTCL] Paint cancelled. No shape selected."))
  467. return
  468. try:
  469. tooldia = float(self.painttooldia_entry.get_value())
  470. except ValueError:
  471. # try to convert comma to decimal point. if it's still not working error message and return
  472. try:
  473. tooldia = float(self.painttooldia_entry.get_value().replace(',', '.'))
  474. self.painttooldia_entry.set_value(tooldia)
  475. except ValueError:
  476. self.app.inform.emit(_("[WARNING_NOTCL] Tool diameter value is missing or wrong format. "
  477. "Add it and retry."))
  478. return
  479. try:
  480. overlap = float(self.paintoverlap_entry.get_value())
  481. except ValueError:
  482. # try to convert comma to decimal point. if it's still not working error message and return
  483. try:
  484. overlap = float(self.paintoverlap_entry.get_value().replace(',', '.'))
  485. self.paintoverlap_entry.set_value(overlap)
  486. except ValueError:
  487. self.app.inform.emit(_("[WARNING_NOTCL] Overlap value is missing or wrong format. "
  488. "Add it and retry."))
  489. return
  490. try:
  491. margin = float(self.paintmargin_entry.get_value())
  492. except ValueError:
  493. # try to convert comma to decimal point. if it's still not working error message and return
  494. try:
  495. margin = float(self.paintmargin_entry.get_value().replace(',', '.'))
  496. self.paintmargin_entry.set_value(margin)
  497. except ValueError:
  498. self.app.inform.emit(_("[WARNING_NOTCL] Margin distance value is missing or wrong format. "
  499. "Add it and retry."))
  500. return
  501. method = self.paintmethod_combo.get_value()
  502. contour = self.paintcontour_cb.get_value()
  503. connect = self.pathconnect_cb.get_value()
  504. self.fcdraw.paint(tooldia, overlap, margin, connect=connect, contour=contour, method=method)
  505. self.fcdraw.select_tool("select")
  506. self.app.ui.notebook.setTabText(2, _("Tools"))
  507. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  508. self.app.ui.splitter.setSizes([0, 1])
  509. class TransformEditorTool(FlatCAMTool):
  510. """
  511. Inputs to specify how to paint the selected polygons.
  512. """
  513. toolName = _("Transform Tool")
  514. rotateName = _("Rotate")
  515. skewName = _("Skew/Shear")
  516. scaleName = _("Scale")
  517. flipName = _("Mirror (Flip)")
  518. offsetName = _("Offset")
  519. def __init__(self, app, draw_app):
  520. FlatCAMTool.__init__(self, app)
  521. self.app = app
  522. self.draw_app = draw_app
  523. self.transform_lay = QtWidgets.QVBoxLayout()
  524. self.layout.addLayout(self.transform_lay)
  525. ## Title
  526. title_label = QtWidgets.QLabel("%s" % (_('Editor %s') % self.toolName))
  527. title_label.setStyleSheet("""
  528. QLabel
  529. {
  530. font-size: 16px;
  531. font-weight: bold;
  532. }
  533. """)
  534. self.transform_lay.addWidget(title_label)
  535. self.empty_label = QtWidgets.QLabel("")
  536. self.empty_label.setFixedWidth(50)
  537. self.empty_label1 = QtWidgets.QLabel("")
  538. self.empty_label1.setFixedWidth(70)
  539. self.empty_label2 = QtWidgets.QLabel("")
  540. self.empty_label2.setFixedWidth(70)
  541. self.empty_label3 = QtWidgets.QLabel("")
  542. self.empty_label3.setFixedWidth(70)
  543. self.empty_label4 = QtWidgets.QLabel("")
  544. self.empty_label4.setFixedWidth(70)
  545. self.transform_lay.addWidget(self.empty_label)
  546. ## Rotate Title
  547. rotate_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.rotateName)
  548. self.transform_lay.addWidget(rotate_title_label)
  549. ## Layout
  550. form_layout = QtWidgets.QFormLayout()
  551. self.transform_lay.addLayout(form_layout)
  552. form_child = QtWidgets.QHBoxLayout()
  553. self.rotate_label = QtWidgets.QLabel(_("Angle:"))
  554. self.rotate_label.setToolTip(
  555. _( "Angle for Rotation action, in degrees.\n"
  556. "Float number between -360 and 359.\n"
  557. "Positive numbers for CW motion.\n"
  558. "Negative numbers for CCW motion.")
  559. )
  560. self.rotate_label.setFixedWidth(50)
  561. self.rotate_entry = FCEntry()
  562. # self.rotate_entry.setFixedWidth(60)
  563. self.rotate_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  564. self.rotate_button = FCButton()
  565. self.rotate_button.set_value(_("Rotate"))
  566. self.rotate_button.setToolTip(
  567. _("Rotate the selected shape(s).\n"
  568. "The point of reference is the middle of\n"
  569. "the bounding box for all selected shapes.")
  570. )
  571. self.rotate_button.setFixedWidth(60)
  572. form_child.addWidget(self.rotate_entry)
  573. form_child.addWidget(self.rotate_button)
  574. form_layout.addRow(self.rotate_label, form_child)
  575. self.transform_lay.addWidget(self.empty_label1)
  576. ## Skew Title
  577. skew_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.skewName)
  578. self.transform_lay.addWidget(skew_title_label)
  579. ## Form Layout
  580. form1_layout = QtWidgets.QFormLayout()
  581. self.transform_lay.addLayout(form1_layout)
  582. form1_child_1 = QtWidgets.QHBoxLayout()
  583. form1_child_2 = QtWidgets.QHBoxLayout()
  584. self.skewx_label = QtWidgets.QLabel(_("Angle X:"))
  585. self.skewx_label.setToolTip(
  586. _( "Angle for Skew action, in degrees.\n"
  587. "Float number between -360 and 359.")
  588. )
  589. self.skewx_label.setFixedWidth(50)
  590. self.skewx_entry = FCEntry()
  591. self.skewx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  592. # self.skewx_entry.setFixedWidth(60)
  593. self.skewx_button = FCButton()
  594. self.skewx_button.set_value(_("Skew X"))
  595. self.skewx_button.setToolTip(
  596. _( "Skew/shear the selected shape(s).\n"
  597. "The point of reference is the middle of\n"
  598. "the bounding box for all selected shapes."))
  599. self.skewx_button.setFixedWidth(60)
  600. self.skewy_label = QtWidgets.QLabel(_("Angle Y:"))
  601. self.skewy_label.setToolTip(
  602. _( "Angle for Skew action, in degrees.\n"
  603. "Float number between -360 and 359.")
  604. )
  605. self.skewy_label.setFixedWidth(50)
  606. self.skewy_entry = FCEntry()
  607. self.skewy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  608. # self.skewy_entry.setFixedWidth(60)
  609. self.skewy_button = FCButton()
  610. self.skewy_button.set_value(_("Skew Y"))
  611. self.skewy_button.setToolTip(
  612. _("Skew/shear the selected shape(s).\n"
  613. "The point of reference is the middle of\n"
  614. "the bounding box for all selected shapes."))
  615. self.skewy_button.setFixedWidth(60)
  616. form1_child_1.addWidget(self.skewx_entry)
  617. form1_child_1.addWidget(self.skewx_button)
  618. form1_child_2.addWidget(self.skewy_entry)
  619. form1_child_2.addWidget(self.skewy_button)
  620. form1_layout.addRow(self.skewx_label, form1_child_1)
  621. form1_layout.addRow(self.skewy_label, form1_child_2)
  622. self.transform_lay.addWidget(self.empty_label2)
  623. ## Scale Title
  624. scale_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.scaleName)
  625. self.transform_lay.addWidget(scale_title_label)
  626. ## Form Layout
  627. form2_layout = QtWidgets.QFormLayout()
  628. self.transform_lay.addLayout(form2_layout)
  629. form2_child_1 = QtWidgets.QHBoxLayout()
  630. form2_child_2 = QtWidgets.QHBoxLayout()
  631. self.scalex_label = QtWidgets.QLabel(_("Factor X:"))
  632. self.scalex_label.setToolTip(
  633. _("Factor for Scale action over X axis.")
  634. )
  635. self.scalex_label.setFixedWidth(50)
  636. self.scalex_entry = FCEntry()
  637. self.scalex_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  638. # self.scalex_entry.setFixedWidth(60)
  639. self.scalex_button = FCButton()
  640. self.scalex_button.set_value(_("Scale X"))
  641. self.scalex_button.setToolTip(
  642. _( "Scale the selected shape(s).\n"
  643. "The point of reference depends on \n"
  644. "the Scale reference checkbox state."))
  645. self.scalex_button.setFixedWidth(60)
  646. self.scaley_label = QtWidgets.QLabel(_("Factor Y:"))
  647. self.scaley_label.setToolTip(
  648. _("Factor for Scale action over Y axis.")
  649. )
  650. self.scaley_label.setFixedWidth(50)
  651. self.scaley_entry = FCEntry()
  652. self.scaley_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  653. # self.scaley_entry.setFixedWidth(60)
  654. self.scaley_button = FCButton()
  655. self.scaley_button.set_value(_("Scale Y"))
  656. self.scaley_button.setToolTip(
  657. _( "Scale the selected shape(s).\n"
  658. "The point of reference depends on \n"
  659. "the Scale reference checkbox state."))
  660. self.scaley_button.setFixedWidth(60)
  661. self.scale_link_cb = FCCheckBox()
  662. self.scale_link_cb.set_value(True)
  663. self.scale_link_cb.setText(_("Link"))
  664. self.scale_link_cb.setToolTip(
  665. _("Scale the selected shape(s)\n"
  666. "using the Scale Factor X for both axis."))
  667. self.scale_link_cb.setFixedWidth(50)
  668. self.scale_zero_ref_cb = FCCheckBox()
  669. self.scale_zero_ref_cb.set_value(True)
  670. self.scale_zero_ref_cb.setText(_("Scale Reference"))
  671. self.scale_zero_ref_cb.setToolTip(
  672. _("Scale the selected shape(s)\n"
  673. "using the origin reference when checked,\n"
  674. "and the center of the biggest bounding box\n"
  675. "of the selected shapes when unchecked."))
  676. form2_child_1.addWidget(self.scalex_entry)
  677. form2_child_1.addWidget(self.scalex_button)
  678. form2_child_2.addWidget(self.scaley_entry)
  679. form2_child_2.addWidget(self.scaley_button)
  680. form2_layout.addRow(self.scalex_label, form2_child_1)
  681. form2_layout.addRow(self.scaley_label, form2_child_2)
  682. form2_layout.addRow(self.scale_link_cb, self.scale_zero_ref_cb)
  683. self.ois_scale = OptionalInputSection(self.scale_link_cb, [self.scaley_entry, self.scaley_button], logic=False)
  684. self.transform_lay.addWidget(self.empty_label3)
  685. ## Offset Title
  686. offset_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.offsetName)
  687. self.transform_lay.addWidget(offset_title_label)
  688. ## Form Layout
  689. form3_layout = QtWidgets.QFormLayout()
  690. self.transform_lay.addLayout(form3_layout)
  691. form3_child_1 = QtWidgets.QHBoxLayout()
  692. form3_child_2 = QtWidgets.QHBoxLayout()
  693. self.offx_label = QtWidgets.QLabel(_("Value X:"))
  694. self.offx_label.setToolTip(
  695. _("Value for Offset action on X axis.")
  696. )
  697. self.offx_label.setFixedWidth(50)
  698. self.offx_entry = FCEntry()
  699. self.offx_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  700. # self.offx_entry.setFixedWidth(60)
  701. self.offx_button = FCButton()
  702. self.offx_button.set_value(_("Offset X"))
  703. self.offx_button.setToolTip(
  704. _( "Offset the selected shape(s).\n"
  705. "The point of reference is the middle of\n"
  706. "the bounding box for all selected shapes.\n")
  707. )
  708. self.offx_button.setFixedWidth(60)
  709. self.offy_label = QtWidgets.QLabel(_("Value Y:"))
  710. self.offy_label.setToolTip(
  711. _("Value for Offset action on Y axis.")
  712. )
  713. self.offy_label.setFixedWidth(50)
  714. self.offy_entry = FCEntry()
  715. self.offy_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  716. # self.offy_entry.setFixedWidth(60)
  717. self.offy_button = FCButton()
  718. self.offy_button.set_value(_("Offset Y"))
  719. self.offy_button.setToolTip(
  720. _("Offset the selected shape(s).\n"
  721. "The point of reference is the middle of\n"
  722. "the bounding box for all selected shapes.\n")
  723. )
  724. self.offy_button.setFixedWidth(60)
  725. form3_child_1.addWidget(self.offx_entry)
  726. form3_child_1.addWidget(self.offx_button)
  727. form3_child_2.addWidget(self.offy_entry)
  728. form3_child_2.addWidget(self.offy_button)
  729. form3_layout.addRow(self.offx_label, form3_child_1)
  730. form3_layout.addRow(self.offy_label, form3_child_2)
  731. self.transform_lay.addWidget(self.empty_label4)
  732. ## Flip Title
  733. flip_title_label = QtWidgets.QLabel("<font size=3><b>%s</b></font>" % self.flipName)
  734. self.transform_lay.addWidget(flip_title_label)
  735. ## Form Layout
  736. form4_layout = QtWidgets.QFormLayout()
  737. form4_child_hlay = QtWidgets.QHBoxLayout()
  738. self.transform_lay.addLayout(form4_child_hlay)
  739. self.transform_lay.addLayout(form4_layout)
  740. form4_child_1 = QtWidgets.QHBoxLayout()
  741. self.flipx_button = FCButton()
  742. self.flipx_button.set_value(_("Flip on X"))
  743. self.flipx_button.setToolTip(
  744. _("Flip the selected shape(s) over the X axis.\n"
  745. "Does not create a new shape.")
  746. )
  747. self.flipx_button.setFixedWidth(60)
  748. self.flipy_button = FCButton()
  749. self.flipy_button.set_value(_("Flip on Y"))
  750. self.flipy_button.setToolTip(
  751. _("Flip the selected shape(s) over the X axis.\n"
  752. "Does not create a new shape.")
  753. )
  754. self.flipy_button.setFixedWidth(60)
  755. self.flip_ref_cb = FCCheckBox()
  756. self.flip_ref_cb.set_value(True)
  757. self.flip_ref_cb.setText(_("Ref Pt"))
  758. self.flip_ref_cb.setToolTip(
  759. _("Flip the selected shape(s)\n"
  760. "around the point in Point Entry Field.\n"
  761. "\n"
  762. "The point coordinates can be captured by\n"
  763. "left click on canvas together with pressing\n"
  764. "SHIFT key. \n"
  765. "Then click Add button to insert coordinates.\n"
  766. "Or enter the coords in format (x, y) in the\n"
  767. "Point Entry field and click Flip on X(Y)")
  768. )
  769. self.flip_ref_cb.setFixedWidth(50)
  770. self.flip_ref_label = QtWidgets.QLabel(_("Point:"))
  771. self.flip_ref_label.setToolTip(
  772. _("Coordinates in format (x, y) used as reference for mirroring.\n"
  773. "The 'x' in (x, y) will be used when using Flip on X and\n"
  774. "the 'y' in (x, y) will be used when using Flip on Y.")
  775. )
  776. self.flip_ref_label.setFixedWidth(50)
  777. self.flip_ref_entry = EvalEntry2("(0, 0)")
  778. self.flip_ref_entry.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
  779. # self.flip_ref_entry.setFixedWidth(60)
  780. self.flip_ref_button = FCButton()
  781. self.flip_ref_button.set_value(_("Add"))
  782. self.flip_ref_button.setToolTip(
  783. _( "The point coordinates can be captured by\n"
  784. "left click on canvas together with pressing\n"
  785. "SHIFT key. Then click Add button to insert.")
  786. )
  787. self.flip_ref_button.setFixedWidth(60)
  788. form4_child_hlay.addStretch()
  789. form4_child_hlay.addWidget(self.flipx_button)
  790. form4_child_hlay.addWidget(self.flipy_button)
  791. form4_child_1.addWidget(self.flip_ref_entry)
  792. form4_child_1.addWidget(self.flip_ref_button)
  793. form4_layout.addRow(self.flip_ref_cb)
  794. form4_layout.addRow(self.flip_ref_label, form4_child_1)
  795. self.ois_flip = OptionalInputSection(self.flip_ref_cb,
  796. [self.flip_ref_entry, self.flip_ref_button], logic=True)
  797. self.transform_lay.addStretch()
  798. ## Signals
  799. self.rotate_button.clicked.connect(self.on_rotate)
  800. self.skewx_button.clicked.connect(self.on_skewx)
  801. self.skewy_button.clicked.connect(self.on_skewy)
  802. self.scalex_button.clicked.connect(self.on_scalex)
  803. self.scaley_button.clicked.connect(self.on_scaley)
  804. self.offx_button.clicked.connect(self.on_offx)
  805. self.offy_button.clicked.connect(self.on_offy)
  806. self.flipx_button.clicked.connect(self.on_flipx)
  807. self.flipy_button.clicked.connect(self.on_flipy)
  808. self.flip_ref_button.clicked.connect(self.on_flip_add_coords)
  809. self.rotate_entry.returnPressed.connect(self.on_rotate)
  810. self.skewx_entry.returnPressed.connect(self.on_skewx)
  811. self.skewy_entry.returnPressed.connect(self.on_skewy)
  812. self.scalex_entry.returnPressed.connect(self.on_scalex)
  813. self.scaley_entry.returnPressed.connect(self.on_scaley)
  814. self.offx_entry.returnPressed.connect(self.on_offx)
  815. self.offy_entry.returnPressed.connect(self.on_offy)
  816. self.set_tool_ui()
  817. def run(self):
  818. self.app.report_usage("Geo Editor Transform Tool()")
  819. FlatCAMTool.run(self)
  820. self.set_tool_ui()
  821. # if the splitter us hidden, display it
  822. if self.app.ui.splitter.sizes()[0] == 0:
  823. self.app.ui.splitter.setSizes([1, 1])
  824. self.app.ui.notebook.setTabText(2, _("Transform Tool"))
  825. def install(self, icon=None, separator=None, **kwargs):
  826. FlatCAMTool.install(self, icon, separator, shortcut='ALT+T', **kwargs)
  827. def set_tool_ui(self):
  828. ## Initialize form
  829. if self.app.defaults["tools_transform_rotate"]:
  830. self.rotate_entry.set_value(self.app.defaults["tools_transform_rotate"])
  831. else:
  832. self.rotate_entry.set_value(0.0)
  833. if self.app.defaults["tools_transform_skew_x"]:
  834. self.skewx_entry.set_value(self.app.defaults["tools_transform_skew_x"])
  835. else:
  836. self.skewx_entry.set_value(0.0)
  837. if self.app.defaults["tools_transform_skew_y"]:
  838. self.skewy_entry.set_value(self.app.defaults["tools_transform_skew_y"])
  839. else:
  840. self.skewy_entry.set_value(0.0)
  841. if self.app.defaults["tools_transform_scale_x"]:
  842. self.scalex_entry.set_value(self.app.defaults["tools_transform_scale_x"])
  843. else:
  844. self.scalex_entry.set_value(1.0)
  845. if self.app.defaults["tools_transform_scale_y"]:
  846. self.scaley_entry.set_value(self.app.defaults["tools_transform_scale_y"])
  847. else:
  848. self.scaley_entry.set_value(1.0)
  849. if self.app.defaults["tools_transform_scale_link"]:
  850. self.scale_link_cb.set_value(self.app.defaults["tools_transform_scale_link"])
  851. else:
  852. self.scale_link_cb.set_value(True)
  853. if self.app.defaults["tools_transform_scale_reference"]:
  854. self.scale_zero_ref_cb.set_value(self.app.defaults["tools_transform_scale_reference"])
  855. else:
  856. self.scale_zero_ref_cb.set_value(True)
  857. if self.app.defaults["tools_transform_offset_x"]:
  858. self.offx_entry.set_value(self.app.defaults["tools_transform_offset_x"])
  859. else:
  860. self.offx_entry.set_value(0.0)
  861. if self.app.defaults["tools_transform_offset_y"]:
  862. self.offy_entry.set_value(self.app.defaults["tools_transform_offset_y"])
  863. else:
  864. self.offy_entry.set_value(0.0)
  865. if self.app.defaults["tools_transform_mirror_reference"]:
  866. self.flip_ref_cb.set_value(self.app.defaults["tools_transform_mirror_reference"])
  867. else:
  868. self.flip_ref_cb.set_value(False)
  869. if self.app.defaults["tools_transform_mirror_point"]:
  870. self.flip_ref_entry.set_value(self.app.defaults["tools_transform_mirror_point"])
  871. else:
  872. self.flip_ref_entry.set_value((0, 0))
  873. def template(self):
  874. if not self.fcdraw.selected:
  875. self.app.inform.emit(_("[WARNING_NOTCL] Transformation cancelled. No shape selected."))
  876. return
  877. self.draw_app.select_tool("select")
  878. self.app.ui.notebook.setTabText(2, "Tools")
  879. self.app.ui.notebook.setCurrentWidget(self.app.ui.project_tab)
  880. self.app.ui.splitter.setSizes([0, 1])
  881. def on_rotate(self, sig=None, val=None):
  882. if val:
  883. value = val
  884. else:
  885. try:
  886. value = float(self.rotate_entry.get_value())
  887. except ValueError:
  888. # try to convert comma to decimal point. if it's still not working error message and return
  889. try:
  890. value = float(self.rotate_entry.get_value().replace(',', '.'))
  891. except ValueError:
  892. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Rotate, "
  893. "use a number."))
  894. return
  895. self.app.worker_task.emit({'fcn': self.on_rotate_action,
  896. 'params': [value]})
  897. # self.on_rotate_action(value)
  898. return
  899. def on_flipx(self):
  900. # self.on_flip("Y")
  901. axis = 'Y'
  902. self.app.worker_task.emit({'fcn': self.on_flip,
  903. 'params': [axis]})
  904. return
  905. def on_flipy(self):
  906. # self.on_flip("X")
  907. axis = 'X'
  908. self.app.worker_task.emit({'fcn': self.on_flip,
  909. 'params': [axis]})
  910. return
  911. def on_flip_add_coords(self):
  912. val = self.app.clipboard.text()
  913. self.flip_ref_entry.set_value(val)
  914. def on_skewx(self, sig=None, val=None):
  915. if val:
  916. value = val
  917. else:
  918. try:
  919. value = float(self.skewx_entry.get_value())
  920. except ValueError:
  921. # try to convert comma to decimal point. if it's still not working error message and return
  922. try:
  923. value = float(self.skewx_entry.get_value().replace(',', '.'))
  924. except ValueError:
  925. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Skew X, "
  926. "use a number."))
  927. return
  928. # self.on_skew("X", value)
  929. axis = 'X'
  930. self.app.worker_task.emit({'fcn': self.on_skew,
  931. 'params': [axis, value]})
  932. return
  933. def on_skewy(self, sig=None, val=None):
  934. if val:
  935. value = val
  936. else:
  937. try:
  938. value = float(self.skewy_entry.get_value())
  939. except ValueError:
  940. # try to convert comma to decimal point. if it's still not working error message and return
  941. try:
  942. value = float(self.skewy_entry.get_value().replace(',', '.'))
  943. except ValueError:
  944. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Skew Y, "
  945. "use a number."))
  946. return
  947. # self.on_skew("Y", value)
  948. axis = 'Y'
  949. self.app.worker_task.emit({'fcn': self.on_skew,
  950. 'params': [axis, value]})
  951. return
  952. def on_scalex(self, sig=None, val=None):
  953. if val:
  954. xvalue = val
  955. else:
  956. try:
  957. xvalue = float(self.scalex_entry.get_value())
  958. except ValueError:
  959. # try to convert comma to decimal point. if it's still not working error message and return
  960. try:
  961. xvalue = float(self.scalex_entry.get_value().replace(',', '.'))
  962. except ValueError:
  963. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Scale X, "
  964. "use a number."))
  965. return
  966. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  967. if xvalue == 0:
  968. xvalue = 1
  969. if self.scale_link_cb.get_value():
  970. yvalue = xvalue
  971. else:
  972. yvalue = 1
  973. axis = 'X'
  974. point = (0, 0)
  975. if self.scale_zero_ref_cb.get_value():
  976. self.app.worker_task.emit({'fcn': self.on_scale,
  977. 'params': [axis, xvalue, yvalue, point]})
  978. # self.on_scale("X", xvalue, yvalue, point=(0,0))
  979. else:
  980. # self.on_scale("X", xvalue, yvalue)
  981. self.app.worker_task.emit({'fcn': self.on_scale,
  982. 'params': [axis, xvalue, yvalue]})
  983. return
  984. def on_scaley(self, sig=None, val=None):
  985. xvalue = 1
  986. if val:
  987. yvalue = val
  988. else:
  989. try:
  990. yvalue = float(self.scaley_entry.get_value())
  991. except ValueError:
  992. # try to convert comma to decimal point. if it's still not working error message and return
  993. try:
  994. yvalue = float(self.scaley_entry.get_value().replace(',', '.'))
  995. except ValueError:
  996. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Scale Y, "
  997. "use a number."))
  998. return
  999. # scaling to zero has no sense so we remove it, because scaling with 1 does nothing
  1000. if yvalue == 0:
  1001. yvalue = 1
  1002. axis = 'Y'
  1003. point = (0, 0)
  1004. if self.scale_zero_ref_cb.get_value():
  1005. self.app.worker_task.emit({'fcn': self.on_scale,
  1006. 'params': [axis, xvalue, yvalue, point]})
  1007. # self.on_scale("Y", xvalue, yvalue, point=(0,0))
  1008. else:
  1009. # self.on_scale("Y", xvalue, yvalue)
  1010. self.app.worker_task.emit({'fcn': self.on_scale,
  1011. 'params': [axis, xvalue, yvalue]})
  1012. return
  1013. def on_offx(self, sig=None, val=None):
  1014. if val:
  1015. value = val
  1016. else:
  1017. try:
  1018. value = float(self.offx_entry.get_value())
  1019. except ValueError:
  1020. # try to convert comma to decimal point. if it's still not working error message and return
  1021. try:
  1022. value = float(self.offx_entry.get_value().replace(',', '.'))
  1023. except ValueError:
  1024. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Offset X, "
  1025. "use a number."))
  1026. return
  1027. # self.on_offset("X", value)
  1028. axis = 'X'
  1029. self.app.worker_task.emit({'fcn': self.on_offset,
  1030. 'params': [axis, value]})
  1031. return
  1032. def on_offy(self, sig=None, val=None):
  1033. if val:
  1034. value = val
  1035. else:
  1036. try:
  1037. value = float(self.offy_entry.get_value())
  1038. except ValueError:
  1039. # try to convert comma to decimal point. if it's still not working error message and return
  1040. try:
  1041. value = float(self.offy_entry.get_value().replace(',', '.'))
  1042. except ValueError:
  1043. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered for Offset Y, "
  1044. "use a number."))
  1045. return
  1046. # self.on_offset("Y", value)
  1047. axis = 'Y'
  1048. self.app.worker_task.emit({'fcn': self.on_offset,
  1049. 'params': [axis, value]})
  1050. return
  1051. def on_rotate_action(self, num):
  1052. shape_list = self.draw_app.selected
  1053. xminlist = []
  1054. yminlist = []
  1055. xmaxlist = []
  1056. ymaxlist = []
  1057. if not shape_list:
  1058. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to rotate!"))
  1059. return
  1060. else:
  1061. with self.app.proc_container.new(_("Appying Rotate")):
  1062. try:
  1063. # first get a bounding box to fit all
  1064. for sha in shape_list:
  1065. xmin, ymin, xmax, ymax = sha.bounds()
  1066. xminlist.append(xmin)
  1067. yminlist.append(ymin)
  1068. xmaxlist.append(xmax)
  1069. ymaxlist.append(ymax)
  1070. # get the minimum x,y and maximum x,y for all objects selected
  1071. xminimal = min(xminlist)
  1072. yminimal = min(yminlist)
  1073. xmaximal = max(xmaxlist)
  1074. ymaximal = max(ymaxlist)
  1075. self.app.progress.emit(20)
  1076. for sel_sha in shape_list:
  1077. px = 0.5 * (xminimal + xmaximal)
  1078. py = 0.5 * (yminimal + ymaximal)
  1079. sel_sha.rotate(-num, point=(px, py))
  1080. self.draw_app.replot()
  1081. # self.draw_app.add_shape(DrawToolShape(sel_sha.geo))
  1082. # self.draw_app.transform_complete.emit()
  1083. self.app.inform.emit(_("[success] Done. Rotate completed."))
  1084. self.app.progress.emit(100)
  1085. except Exception as e:
  1086. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  1087. return
  1088. def on_flip(self, axis):
  1089. shape_list = self.draw_app.selected
  1090. xminlist = []
  1091. yminlist = []
  1092. xmaxlist = []
  1093. ymaxlist = []
  1094. if not shape_list:
  1095. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to flip!"))
  1096. return
  1097. else:
  1098. with self.app.proc_container.new(_("Applying Flip")):
  1099. try:
  1100. # get mirroring coords from the point entry
  1101. if self.flip_ref_cb.isChecked():
  1102. px, py = eval('{}'.format(self.flip_ref_entry.text()))
  1103. # get mirroing coords from the center of an all-enclosing bounding box
  1104. else:
  1105. # first get a bounding box to fit all
  1106. for sha in shape_list:
  1107. xmin, ymin, xmax, ymax = sha.bounds()
  1108. xminlist.append(xmin)
  1109. yminlist.append(ymin)
  1110. xmaxlist.append(xmax)
  1111. ymaxlist.append(ymax)
  1112. # get the minimum x,y and maximum x,y for all objects selected
  1113. xminimal = min(xminlist)
  1114. yminimal = min(yminlist)
  1115. xmaximal = max(xmaxlist)
  1116. ymaximal = max(ymaxlist)
  1117. px = 0.5 * (xminimal + xmaximal)
  1118. py = 0.5 * (yminimal + ymaximal)
  1119. self.app.progress.emit(20)
  1120. # execute mirroring
  1121. for sha in shape_list:
  1122. if axis is 'X':
  1123. sha.mirror('X', (px, py))
  1124. self.app.inform.emit(_('[success] Flip on the Y axis done ...'))
  1125. elif axis is 'Y':
  1126. sha.mirror('Y', (px, py))
  1127. self.app.inform.emit(_('[success] Flip on the X axis done ...'))
  1128. self.draw_app.replot()
  1129. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1130. #
  1131. # self.draw_app.transform_complete.emit()
  1132. self.app.progress.emit(100)
  1133. except Exception as e:
  1134. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  1135. return
  1136. def on_skew(self, axis, num):
  1137. shape_list = self.draw_app.selected
  1138. xminlist = []
  1139. yminlist = []
  1140. if not shape_list:
  1141. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to shear/skew!"))
  1142. return
  1143. else:
  1144. with self.app.proc_container.new(_("Applying Skew")):
  1145. try:
  1146. # first get a bounding box to fit all
  1147. for sha in shape_list:
  1148. xmin, ymin, xmax, ymax = sha.bounds()
  1149. xminlist.append(xmin)
  1150. yminlist.append(ymin)
  1151. # get the minimum x,y and maximum x,y for all objects selected
  1152. xminimal = min(xminlist)
  1153. yminimal = min(yminlist)
  1154. self.app.progress.emit(20)
  1155. for sha in shape_list:
  1156. if axis is 'X':
  1157. sha.skew(num, 0, point=(xminimal, yminimal))
  1158. elif axis is 'Y':
  1159. sha.skew(0, num, point=(xminimal, yminimal))
  1160. self.draw_app.replot()
  1161. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1162. #
  1163. # self.draw_app.transform_complete.emit()
  1164. self.app.inform.emit(_('[success] Skew on the %s axis done ...') % str(axis))
  1165. self.app.progress.emit(100)
  1166. except Exception as e:
  1167. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Skew action was not executed.") % str(e))
  1168. return
  1169. def on_scale(self, axis, xfactor, yfactor, point=None):
  1170. shape_list = self.draw_app.selected
  1171. xminlist = []
  1172. yminlist = []
  1173. xmaxlist = []
  1174. ymaxlist = []
  1175. if not shape_list:
  1176. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to scale!"))
  1177. return
  1178. else:
  1179. with self.app.proc_container.new(_("Applying Scale")):
  1180. try:
  1181. # first get a bounding box to fit all
  1182. for sha in shape_list:
  1183. xmin, ymin, xmax, ymax = sha.bounds()
  1184. xminlist.append(xmin)
  1185. yminlist.append(ymin)
  1186. xmaxlist.append(xmax)
  1187. ymaxlist.append(ymax)
  1188. # get the minimum x,y and maximum x,y for all objects selected
  1189. xminimal = min(xminlist)
  1190. yminimal = min(yminlist)
  1191. xmaximal = max(xmaxlist)
  1192. ymaximal = max(ymaxlist)
  1193. self.app.progress.emit(20)
  1194. if point is None:
  1195. px = 0.5 * (xminimal + xmaximal)
  1196. py = 0.5 * (yminimal + ymaximal)
  1197. else:
  1198. px = 0
  1199. py = 0
  1200. for sha in shape_list:
  1201. sha.scale(xfactor, yfactor, point=(px, py))
  1202. self.draw_app.replot()
  1203. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1204. #
  1205. # self.draw_app.transform_complete.emit()
  1206. self.app.inform.emit(_('[success] Scale on the %s axis done ...') % str(axis))
  1207. self.app.progress.emit(100)
  1208. except Exception as e:
  1209. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Scale action was not executed.") % str(e))
  1210. return
  1211. def on_offset(self, axis, num):
  1212. shape_list = self.draw_app.selected
  1213. xminlist = []
  1214. yminlist = []
  1215. if not shape_list:
  1216. self.app.inform.emit(_("[WARNING_NOTCL] No shape selected. Please Select a shape to offset!"))
  1217. return
  1218. else:
  1219. with self.app.proc_container.new(_("Applying Offset")):
  1220. try:
  1221. # first get a bounding box to fit all
  1222. for sha in shape_list:
  1223. xmin, ymin, xmax, ymax = sha.bounds()
  1224. xminlist.append(xmin)
  1225. yminlist.append(ymin)
  1226. # get the minimum x,y and maximum x,y for all objects selected
  1227. xminimal = min(xminlist)
  1228. yminimal = min(yminlist)
  1229. self.app.progress.emit(20)
  1230. for sha in shape_list:
  1231. if axis is 'X':
  1232. sha.offset((num, 0))
  1233. elif axis is 'Y':
  1234. sha.offset((0, num))
  1235. self.draw_app.replot()
  1236. # self.draw_app.add_shape(DrawToolShape(sha.geo))
  1237. #
  1238. # self.draw_app.transform_complete.emit()
  1239. self.app.inform.emit(_('[success] Offset on the %s axis done ...') % str(axis))
  1240. self.app.progress.emit(100)
  1241. except Exception as e:
  1242. self.app.inform.emit(_("[ERROR_NOTCL] Due of %s, Offset action was not executed.") % str(e))
  1243. return
  1244. def on_rotate_key(self):
  1245. val_box = FCInputDialog(title=_("Rotate ..."),
  1246. text=_('Enter an Angle Value (degrees):'),
  1247. min=-359.9999, max=360.0000, decimals=4,
  1248. init_val=float(self.app.defaults['tools_transform_rotate']))
  1249. val_box.setWindowIcon(QtGui.QIcon('share/rotate.png'))
  1250. val, ok = val_box.get_value()
  1251. if ok:
  1252. self.on_rotate(val=val)
  1253. self.app.inform.emit(
  1254. _("[success] Geometry shape rotate done...")
  1255. )
  1256. return
  1257. else:
  1258. self.app.inform.emit(
  1259. _("[WARNING_NOTCL] Geometry shape rotate cancelled...")
  1260. )
  1261. def on_offx_key(self):
  1262. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1263. val_box = FCInputDialog(title=_("Offset on X axis ..."),
  1264. text=(_('Enter a distance Value (%s):') % str(units)),
  1265. min=-9999.9999, max=10000.0000, decimals=4,
  1266. init_val=float(self.app.defaults['tools_transform_offset_x']))
  1267. val_box.setWindowIcon(QtGui.QIcon('share/offsetx32.png'))
  1268. val, ok = val_box.get_value()
  1269. if ok:
  1270. self.on_offx(val=val)
  1271. self.app.inform.emit(
  1272. _("[success] Geometry shape offset on X axis done..."))
  1273. return
  1274. else:
  1275. self.app.inform.emit(
  1276. _("[WARNING_NOTCL] Geometry shape offset X cancelled..."))
  1277. def on_offy_key(self):
  1278. units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  1279. val_box = FCInputDialog(title=_("Offset on Y axis ..."),
  1280. text=(_('Enter a distance Value (%s):') % str(units)),
  1281. min=-9999.9999, max=10000.0000, decimals=4,
  1282. init_val=float(self.app.defaults['tools_transform_offset_y']))
  1283. val_box.setWindowIcon(QtGui.QIcon('share/offsety32.png'))
  1284. val, ok = val_box.get_value()
  1285. if ok:
  1286. self.on_offx(val=val)
  1287. self.app.inform.emit(
  1288. _("[success] Geometry shape offset on Y axis done..."))
  1289. return
  1290. else:
  1291. self.app.inform.emit(
  1292. _("[WARNING_NOTCL] Geometry shape offset Y cancelled..."))
  1293. def on_skewx_key(self):
  1294. val_box = FCInputDialog(title=_("Skew on X axis ..."),
  1295. text=_('Enter an Angle Value (degrees):'),
  1296. min=-359.9999, max=360.0000, decimals=4,
  1297. init_val=float(self.app.defaults['tools_transform_skew_x']))
  1298. val_box.setWindowIcon(QtGui.QIcon('share/skewX.png'))
  1299. val, ok = val_box.get_value()
  1300. if ok:
  1301. self.on_skewx(val=val)
  1302. self.app.inform.emit(
  1303. _("[success] Geometry shape skew on X axis done..."))
  1304. return
  1305. else:
  1306. self.app.inform.emit(
  1307. _( "[WARNING_NOTCL] Geometry shape skew X cancelled..."))
  1308. def on_skewy_key(self):
  1309. val_box = FCInputDialog(title=_("Skew on Y axis ..."),
  1310. text=_('Enter an Angle Value (degrees):'),
  1311. min=-359.9999, max=360.0000, decimals=4,
  1312. init_val=float(self.app.defaults['tools_transform_skew_y']))
  1313. val_box.setWindowIcon(QtGui.QIcon('share/skewY.png'))
  1314. val, ok = val_box.get_value()
  1315. if ok:
  1316. self.on_skewx(val=val)
  1317. self.app.inform.emit(
  1318. _( "[success] Geometry shape skew on Y axis done..."))
  1319. return
  1320. else:
  1321. self.app.inform.emit(
  1322. _("[WARNING_NOTCL] Geometry shape skew Y cancelled..."))
  1323. class DrawToolShape(object):
  1324. """
  1325. Encapsulates "shapes" under a common class.
  1326. """
  1327. tolerance = None
  1328. @staticmethod
  1329. def get_pts(o):
  1330. """
  1331. Returns a list of all points in the object, where
  1332. the object can be a Polygon, Not a polygon, or a list
  1333. of such. Search is done recursively.
  1334. :param: geometric object
  1335. :return: List of points
  1336. :rtype: list
  1337. """
  1338. pts = []
  1339. ## Iterable: descend into each item.
  1340. try:
  1341. for subo in o:
  1342. pts += DrawToolShape.get_pts(subo)
  1343. ## Non-iterable
  1344. except TypeError:
  1345. if o is not None:
  1346. ## DrawToolShape: descend into .geo.
  1347. if isinstance(o, DrawToolShape):
  1348. pts += DrawToolShape.get_pts(o.geo)
  1349. ## Descend into .exerior and .interiors
  1350. elif type(o) == Polygon:
  1351. pts += DrawToolShape.get_pts(o.exterior)
  1352. for i in o.interiors:
  1353. pts += DrawToolShape.get_pts(i)
  1354. elif type(o) == MultiLineString:
  1355. for line in o:
  1356. pts += DrawToolShape.get_pts(line)
  1357. ## Has .coords: list them.
  1358. else:
  1359. if DrawToolShape.tolerance is not None:
  1360. pts += list(o.simplify(DrawToolShape.tolerance).coords)
  1361. else:
  1362. pts += list(o.coords)
  1363. else:
  1364. return
  1365. return pts
  1366. def __init__(self, geo=[]):
  1367. # Shapely type or list of such
  1368. self.geo = geo
  1369. self.utility = False
  1370. def get_all_points(self):
  1371. return DrawToolShape.get_pts(self)
  1372. def bounds(self):
  1373. """
  1374. Returns coordinates of rectangular bounds
  1375. of geometry: (xmin, ymin, xmax, ymax).
  1376. """
  1377. # fixed issue of getting bounds only for one level lists of objects
  1378. # now it can get bounds for nested lists of objects
  1379. def bounds_rec(shape):
  1380. if type(shape) is list:
  1381. minx = Inf
  1382. miny = Inf
  1383. maxx = -Inf
  1384. maxy = -Inf
  1385. for k in shape:
  1386. minx_, miny_, maxx_, maxy_ = bounds_rec(k)
  1387. minx = min(minx, minx_)
  1388. miny = min(miny, miny_)
  1389. maxx = max(maxx, maxx_)
  1390. maxy = max(maxy, maxy_)
  1391. return minx, miny, maxx, maxy
  1392. else:
  1393. # it's a Shapely object, return it's bounds
  1394. return shape.bounds
  1395. bounds_coords = bounds_rec(self.geo)
  1396. return bounds_coords
  1397. def mirror(self, axis, point):
  1398. """
  1399. Mirrors the shape around a specified axis passing through
  1400. the given point.
  1401. :param axis: "X" or "Y" indicates around which axis to mirror.
  1402. :type axis: str
  1403. :param point: [x, y] point belonging to the mirror axis.
  1404. :type point: list
  1405. :return: None
  1406. """
  1407. px, py = point
  1408. xscale, yscale = {"X": (1.0, -1.0), "Y": (-1.0, 1.0)}[axis]
  1409. def mirror_geom(shape):
  1410. if type(shape) is list:
  1411. new_obj = []
  1412. for g in shape:
  1413. new_obj.append(mirror_geom(g))
  1414. return new_obj
  1415. else:
  1416. return affinity.scale(shape, xscale, yscale, origin=(px,py))
  1417. try:
  1418. self.geo = mirror_geom(self.geo)
  1419. except AttributeError:
  1420. log.debug("DrawToolShape.mirror() --> Failed to mirror. No shape selected")
  1421. def rotate(self, angle, point):
  1422. """
  1423. Rotate a shape by an angle (in degrees) around the provided coordinates.
  1424. Parameters
  1425. ----------
  1426. The angle of rotation are specified in degrees (default). Positive angles are
  1427. counter-clockwise and negative are clockwise rotations.
  1428. The point of origin can be a keyword 'center' for the bounding box
  1429. center (default), 'centroid' for the geometry's centroid, a Point object
  1430. or a coordinate tuple (x0, y0).
  1431. See shapely manual for more information:
  1432. http://toblerity.org/shapely/manual.html#affine-transformations
  1433. """
  1434. px, py = point
  1435. def rotate_geom(shape):
  1436. if type(shape) is list:
  1437. new_obj = []
  1438. for g in shape:
  1439. new_obj.append(rotate_geom(g))
  1440. return new_obj
  1441. else:
  1442. return affinity.rotate(shape, angle, origin=(px, py))
  1443. try:
  1444. self.geo = rotate_geom(self.geo)
  1445. except AttributeError:
  1446. log.debug("DrawToolShape.rotate() --> Failed to rotate. No shape selected")
  1447. def skew(self, angle_x, angle_y, point):
  1448. """
  1449. Shear/Skew a shape by angles along x and y dimensions.
  1450. Parameters
  1451. ----------
  1452. angle_x, angle_y : float, float
  1453. The shear angle(s) for the x and y axes respectively. These can be
  1454. specified in either degrees (default) or radians by setting
  1455. use_radians=True.
  1456. point: tuple of coordinates (x,y)
  1457. See shapely manual for more information:
  1458. http://toblerity.org/shapely/manual.html#affine-transformations
  1459. """
  1460. px, py = point
  1461. def skew_geom(shape):
  1462. if type(shape) is list:
  1463. new_obj = []
  1464. for g in shape:
  1465. new_obj.append(skew_geom(g))
  1466. return new_obj
  1467. else:
  1468. return affinity.skew(shape, angle_x, angle_y, origin=(px, py))
  1469. try:
  1470. self.geo = skew_geom(self.geo)
  1471. except AttributeError:
  1472. log.debug("DrawToolShape.skew() --> Failed to skew. No shape selected")
  1473. def offset(self, vect):
  1474. """
  1475. Offsets all shapes by a given vector/
  1476. :param vect: (x, y) vector by which to offset the shape geometry
  1477. :type vect: tuple
  1478. :return: None
  1479. :rtype: None
  1480. """
  1481. try:
  1482. dx, dy = vect
  1483. except TypeError:
  1484. log.debug("DrawToolShape.offset() --> An (x,y) pair of values are needed. "
  1485. "Probable you entered only one value in the Offset field.")
  1486. return
  1487. def translate_recursion(geom):
  1488. if type(geom) == list:
  1489. geoms=list()
  1490. for local_geom in geom:
  1491. geoms.append(translate_recursion(local_geom))
  1492. return geoms
  1493. else:
  1494. return affinity.translate(geom, xoff=dx, yoff=dy)
  1495. try:
  1496. self.geo = translate_recursion(self.geo)
  1497. except AttributeError:
  1498. log.debug("DrawToolShape.offset() --> Failed to offset. No shape selected")
  1499. def scale(self, xfactor, yfactor=None, point=None):
  1500. """
  1501. Scales all shape geometry by a given factor.
  1502. :param xfactor: Factor by which to scale the shape's geometry/
  1503. :type xfactor: float
  1504. :param yfactor: Factor by which to scale the shape's geometry/
  1505. :type yfactor: float
  1506. :return: None
  1507. :rtype: None
  1508. """
  1509. try:
  1510. xfactor = float(xfactor)
  1511. except:
  1512. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1513. return
  1514. if yfactor is None:
  1515. yfactor = xfactor
  1516. else:
  1517. try:
  1518. yfactor = float(yfactor)
  1519. except:
  1520. log.debug("DrawToolShape.offset() --> Scale factor has to be a number: integer or float.")
  1521. return
  1522. if point is None:
  1523. px = 0
  1524. py = 0
  1525. else:
  1526. px, py = point
  1527. def scale_recursion(geom):
  1528. if type(geom) == list:
  1529. geoms=list()
  1530. for local_geom in geom:
  1531. geoms.append(scale_recursion(local_geom))
  1532. return geoms
  1533. else:
  1534. return affinity.scale(geom, xfactor, yfactor, origin=(px, py))
  1535. try:
  1536. self.geo = scale_recursion(self.geo)
  1537. except AttributeError:
  1538. log.debug("DrawToolShape.scale() --> Failed to scale. No shape selected")
  1539. class DrawToolUtilityShape(DrawToolShape):
  1540. """
  1541. Utility shapes are temporary geometry in the editor
  1542. to assist in the creation of shapes. For example it
  1543. will show the outline of a rectangle from the first
  1544. point to the current mouse pointer before the second
  1545. point is clicked and the final geometry is created.
  1546. """
  1547. def __init__(self, geo=[]):
  1548. super(DrawToolUtilityShape, self).__init__(geo=geo)
  1549. self.utility = True
  1550. class DrawTool(object):
  1551. """
  1552. Abstract Class representing a tool in the drawing
  1553. program. Can generate geometry, including temporary
  1554. utility geometry that is updated on user clicks
  1555. and mouse motion.
  1556. """
  1557. def __init__(self, draw_app):
  1558. self.draw_app = draw_app
  1559. self.complete = False
  1560. self.start_msg = "Click on 1st point..."
  1561. self.points = []
  1562. self.geometry = None # DrawToolShape or None
  1563. def click(self, point):
  1564. """
  1565. :param point: [x, y] Coordinate pair.
  1566. """
  1567. return ""
  1568. def click_release(self, point):
  1569. """
  1570. :param point: [x, y] Coordinate pair.
  1571. """
  1572. return ""
  1573. def on_key(self, key):
  1574. return None
  1575. def utility_geometry(self, data=None):
  1576. return None
  1577. class FCShapeTool(DrawTool):
  1578. """
  1579. Abstract class for tools that create a shape.
  1580. """
  1581. def __init__(self, draw_app):
  1582. DrawTool.__init__(self, draw_app)
  1583. def make(self):
  1584. pass
  1585. class FCCircle(FCShapeTool):
  1586. """
  1587. Resulting type: Polygon
  1588. """
  1589. def __init__(self, draw_app):
  1590. DrawTool.__init__(self, draw_app)
  1591. self.name = 'circle'
  1592. self.start_msg = _("Click on CENTER ...")
  1593. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1594. def click(self, point):
  1595. self.points.append(point)
  1596. if len(self.points) == 1:
  1597. self.draw_app.app.inform.emit(_("Click on Circle perimeter point to complete ..."))
  1598. return "Click on perimeter to complete ..."
  1599. if len(self.points) == 2:
  1600. self.make()
  1601. return "Done."
  1602. return ""
  1603. def utility_geometry(self, data=None):
  1604. if len(self.points) == 1:
  1605. p1 = self.points[0]
  1606. p2 = data
  1607. radius = sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
  1608. return DrawToolUtilityShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1609. return None
  1610. def make(self):
  1611. p1 = self.points[0]
  1612. p2 = self.points[1]
  1613. radius = distance(p1, p2)
  1614. self.geometry = DrawToolShape(Point(p1).buffer(radius, int(self.steps_per_circ / 4)))
  1615. self.complete = True
  1616. self.draw_app.app.inform.emit(_("[success]Done. Adding Circle completed."))
  1617. class FCArc(FCShapeTool):
  1618. def __init__(self, draw_app):
  1619. DrawTool.__init__(self, draw_app)
  1620. self.name = 'arc'
  1621. self.start_msg = _("Click on CENTER ...")
  1622. # Direction of rotation between point 1 and 2.
  1623. # 'cw' or 'ccw'. Switch direction by hitting the
  1624. # 'o' key.
  1625. self.direction = "cw"
  1626. # Mode
  1627. # C12 = Center, p1, p2
  1628. # 12C = p1, p2, Center
  1629. # 132 = p1, p3, p2
  1630. self.mode = "c12" # Center, p1, p2
  1631. self.steps_per_circ = self.draw_app.app.defaults["geometry_circle_steps"]
  1632. def click(self, point):
  1633. self.points.append(point)
  1634. if len(self.points) == 1:
  1635. self.draw_app.app.inform.emit(_("Click on Start arc point ..."))
  1636. return "Click on 1st point ..."
  1637. if len(self.points) == 2:
  1638. self.draw_app.app.inform.emit(_("Click on End arc point to complete ..."))
  1639. return "Click on 2nd point to complete ..."
  1640. if len(self.points) == 3:
  1641. self.make()
  1642. return "Done."
  1643. return ""
  1644. def on_key(self, key):
  1645. if key == 'o':
  1646. self.direction = 'cw' if self.direction == 'ccw' else 'ccw'
  1647. return 'Direction: ' + self.direction.upper()
  1648. if key == 'p':
  1649. if self.mode == 'c12':
  1650. self.mode = '12c'
  1651. elif self.mode == '12c':
  1652. self.mode = '132'
  1653. else:
  1654. self.mode = 'c12'
  1655. return 'Mode: ' + self.mode
  1656. def utility_geometry(self, data=None):
  1657. if len(self.points) == 1: # Show the radius
  1658. center = self.points[0]
  1659. p1 = data
  1660. return DrawToolUtilityShape(LineString([center, p1]))
  1661. if len(self.points) == 2: # Show the arc
  1662. if self.mode == 'c12':
  1663. center = self.points[0]
  1664. p1 = self.points[1]
  1665. p2 = data
  1666. radius = sqrt((center[0] - p1[0]) ** 2 + (center[1] - p1[1]) ** 2)
  1667. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1668. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1669. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1670. self.direction, self.steps_per_circ)),
  1671. Point(center)])
  1672. elif self.mode == '132':
  1673. p1 = array(self.points[0])
  1674. p3 = array(self.points[1])
  1675. p2 = array(data)
  1676. center, radius, t = three_point_circle(p1, p2, p3)
  1677. direction = 'cw' if sign(t) > 0 else 'ccw'
  1678. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1679. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1680. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1681. direction, self.steps_per_circ)),
  1682. Point(center), Point(p1), Point(p3)])
  1683. else: # '12c'
  1684. p1 = array(self.points[0])
  1685. p2 = array(self.points[1])
  1686. # Midpoint
  1687. a = (p1 + p2) / 2.0
  1688. # Parallel vector
  1689. c = p2 - p1
  1690. # Perpendicular vector
  1691. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1692. b /= norm(b)
  1693. # Distance
  1694. t = distance(data, a)
  1695. # Which side? Cross product with c.
  1696. # cross(M-A, B-A), where line is AB and M is test point.
  1697. side = (data[0] - p1[0]) * c[1] - (data[1] - p1[1]) * c[0]
  1698. t *= sign(side)
  1699. # Center = a + bt
  1700. center = a + b * t
  1701. radius = norm(center - p1)
  1702. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1703. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1704. return DrawToolUtilityShape([LineString(arc(center, radius, startangle, stopangle,
  1705. self.direction, self.steps_per_circ)),
  1706. Point(center)])
  1707. return None
  1708. def make(self):
  1709. if self.mode == 'c12':
  1710. center = self.points[0]
  1711. p1 = self.points[1]
  1712. p2 = self.points[2]
  1713. radius = distance(center, p1)
  1714. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1715. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1716. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1717. self.direction, self.steps_per_circ)))
  1718. elif self.mode == '132':
  1719. p1 = array(self.points[0])
  1720. p3 = array(self.points[1])
  1721. p2 = array(self.points[2])
  1722. center, radius, t = three_point_circle(p1, p2, p3)
  1723. direction = 'cw' if sign(t) > 0 else 'ccw'
  1724. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1725. stopangle = arctan2(p3[1] - center[1], p3[0] - center[0])
  1726. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1727. direction, self.steps_per_circ)))
  1728. else: # self.mode == '12c'
  1729. p1 = array(self.points[0])
  1730. p2 = array(self.points[1])
  1731. pc = array(self.points[2])
  1732. # Midpoint
  1733. a = (p1 + p2) / 2.0
  1734. # Parallel vector
  1735. c = p2 - p1
  1736. # Perpendicular vector
  1737. b = dot(c, array([[0, -1], [1, 0]], dtype=float32))
  1738. b /= norm(b)
  1739. # Distance
  1740. t = distance(pc, a)
  1741. # Which side? Cross product with c.
  1742. # cross(M-A, B-A), where line is AB and M is test point.
  1743. side = (pc[0] - p1[0]) * c[1] - (pc[1] - p1[1]) * c[0]
  1744. t *= sign(side)
  1745. # Center = a + bt
  1746. center = a + b * t
  1747. radius = norm(center - p1)
  1748. startangle = arctan2(p1[1] - center[1], p1[0] - center[0])
  1749. stopangle = arctan2(p2[1] - center[1], p2[0] - center[0])
  1750. self.geometry = DrawToolShape(LineString(arc(center, radius, startangle, stopangle,
  1751. self.direction, self.steps_per_circ)))
  1752. self.complete = True
  1753. self.draw_app.app.inform.emit(_("[success]Done. Arc completed."))
  1754. class FCRectangle(FCShapeTool):
  1755. """
  1756. Resulting type: Polygon
  1757. """
  1758. def __init__(self, draw_app):
  1759. DrawTool.__init__(self, draw_app)
  1760. self.name = 'rectangle'
  1761. self.start_msg = _("Click on 1st corner ...")
  1762. def click(self, point):
  1763. self.points.append(point)
  1764. if len(self.points) == 1:
  1765. return "Click on opposite corner to complete ..."
  1766. if len(self.points) == 2:
  1767. self.make()
  1768. return "Done."
  1769. return ""
  1770. def utility_geometry(self, data=None):
  1771. if len(self.points) == 1:
  1772. p1 = self.points[0]
  1773. p2 = data
  1774. return DrawToolUtilityShape(LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1775. return None
  1776. def make(self):
  1777. p1 = self.points[0]
  1778. p2 = self.points[1]
  1779. # self.geometry = LinearRing([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])])
  1780. self.geometry = DrawToolShape(Polygon([p1, (p2[0], p1[1]), p2, (p1[0], p2[1])]))
  1781. self.complete = True
  1782. self.draw_app.app.inform.emit("_([success]Done. Rectangle completed.")
  1783. class FCPolygon(FCShapeTool):
  1784. """
  1785. Resulting type: Polygon
  1786. """
  1787. def __init__(self, draw_app):
  1788. DrawTool.__init__(self, draw_app)
  1789. self.name = 'polygon'
  1790. self.start_msg = _("Click on 1st point ...")
  1791. def click(self, point):
  1792. self.draw_app.in_action = True
  1793. self.points.append(point)
  1794. if len(self.points) > 0:
  1795. self.draw_app.app.inform.emit(_("Click on next Point or click Right mouse button to complete ..."))
  1796. return "Click on next point or hit ENTER to complete ..."
  1797. return ""
  1798. def utility_geometry(self, data=None):
  1799. if len(self.points) == 1:
  1800. temp_points = [x for x in self.points]
  1801. temp_points.append(data)
  1802. return DrawToolUtilityShape(LineString(temp_points))
  1803. if len(self.points) > 1:
  1804. temp_points = [x for x in self.points]
  1805. temp_points.append(data)
  1806. return DrawToolUtilityShape(LinearRing(temp_points))
  1807. return None
  1808. def make(self):
  1809. # self.geometry = LinearRing(self.points)
  1810. self.geometry = DrawToolShape(Polygon(self.points))
  1811. self.draw_app.in_action = False
  1812. self.complete = True
  1813. self.draw_app.app.inform.emit(_("[success]Done. Polygon completed."))
  1814. def on_key(self, key):
  1815. if key == 'backspace':
  1816. if len(self.points) > 0:
  1817. self.points = self.points[0:-1]
  1818. class FCPath(FCPolygon):
  1819. """
  1820. Resulting type: LineString
  1821. """
  1822. def make(self):
  1823. self.geometry = DrawToolShape(LineString(self.points))
  1824. self.name = 'path'
  1825. self.draw_app.in_action = False
  1826. self.complete = True
  1827. self.draw_app.app.inform.emit(_("[success]Done. Path completed."))
  1828. def utility_geometry(self, data=None):
  1829. if len(self.points) > 0:
  1830. temp_points = [x for x in self.points]
  1831. temp_points.append(data)
  1832. return DrawToolUtilityShape(LineString(temp_points))
  1833. return None
  1834. def on_key(self, key):
  1835. if key == 'backspace':
  1836. if len(self.points) > 0:
  1837. self.points = self.points[0:-1]
  1838. class FCSelect(DrawTool):
  1839. def __init__(self, draw_app):
  1840. DrawTool.__init__(self, draw_app)
  1841. self.name = 'select'
  1842. self.storage = self.draw_app.storage
  1843. # self.shape_buffer = self.draw_app.shape_buffer
  1844. # self.selected = self.draw_app.selected
  1845. def click_release(self, point):
  1846. self.select_shapes(point)
  1847. return ""
  1848. def select_shapes(self, pos):
  1849. # list where we store the overlapped shapes under our mouse left click position
  1850. over_shape_list = []
  1851. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1852. for obj_shape in self.storage.get_objects():
  1853. # first method of click selection -> inconvenient
  1854. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1855. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1856. # over_shape_list.append(obj_shape)
  1857. # second method of click selection -> slow
  1858. # outside = obj_shape.geo.buffer(0.1)
  1859. # inside = obj_shape.geo.buffer(-0.1)
  1860. # shape_band = outside.difference(inside)
  1861. # if Point(pos).within(shape_band):
  1862. # over_shape_list.append(obj_shape)
  1863. # 3rd method of click selection -> inconvenient
  1864. try:
  1865. _, closest_shape = self.storage.nearest(pos)
  1866. except StopIteration:
  1867. return ""
  1868. over_shape_list.append(closest_shape)
  1869. try:
  1870. # if there is no shape under our click then deselect all shapes
  1871. # it will not work for 3rd method of click selection
  1872. if not over_shape_list:
  1873. self.draw_app.selected = []
  1874. FlatCAMGeoEditor.draw_shape_idx = -1
  1875. else:
  1876. # if there are shapes under our click then advance through the list of them, one at the time in a
  1877. # circular way
  1878. FlatCAMGeoEditor.draw_shape_idx = (FlatCAMGeoEditor.draw_shape_idx + 1) % len(over_shape_list)
  1879. obj_to_add = over_shape_list[int(FlatCAMGeoEditor.draw_shape_idx)]
  1880. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1881. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  1882. # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1883. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1884. if key_modifier == Qt.ControlModifier:
  1885. if obj_to_add in self.draw_app.selected:
  1886. self.draw_app.selected.remove(obj_to_add)
  1887. else:
  1888. self.draw_app.selected.append(obj_to_add)
  1889. else:
  1890. self.draw_app.selected = []
  1891. self.draw_app.selected.append(obj_to_add)
  1892. else:
  1893. if key_modifier == Qt.ShiftModifier:
  1894. if obj_to_add in self.draw_app.selected:
  1895. self.draw_app.selected.remove(obj_to_add)
  1896. else:
  1897. self.draw_app.selected.append(obj_to_add)
  1898. else:
  1899. self.draw_app.selected = []
  1900. self.draw_app.selected.append(obj_to_add)
  1901. except Exception as e:
  1902. log.error("[ERROR] Something went bad. %s" % str(e))
  1903. raise
  1904. class FCDrillSelect(DrawTool):
  1905. def __init__(self, exc_editor_app):
  1906. DrawTool.__init__(self, exc_editor_app)
  1907. self.name = 'drill_select'
  1908. self.exc_editor_app = exc_editor_app
  1909. self.storage = self.exc_editor_app.storage_dict
  1910. # self.selected = self.exc_editor_app.selected
  1911. # here we store all shapes that were selected so we can search for the nearest to our click location
  1912. self.sel_storage = FlatCAMExcEditor.make_storage()
  1913. self.exc_editor_app.resize_frame.hide()
  1914. self.exc_editor_app.array_frame.hide()
  1915. def click(self, point):
  1916. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1917. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  1918. if key_modifier == Qt.ControlModifier:
  1919. pass
  1920. else:
  1921. self.exc_editor_app.selected = []
  1922. else:
  1923. if key_modifier == Qt.ShiftModifier:
  1924. pass
  1925. else:
  1926. self.exc_editor_app.selected = []
  1927. def click_release(self, point):
  1928. self.select_shapes(point)
  1929. return ""
  1930. def select_shapes(self, pos):
  1931. self.exc_editor_app.tools_table_exc.clearSelection()
  1932. try:
  1933. # for storage in self.exc_editor_app.storage_dict:
  1934. # _, partial_closest_shape = self.exc_editor_app.storage_dict[storage].nearest(pos)
  1935. # if partial_closest_shape is not None:
  1936. # self.sel_storage.insert(partial_closest_shape)
  1937. #
  1938. # _, closest_shape = self.sel_storage.nearest(pos)
  1939. for storage in self.exc_editor_app.storage_dict:
  1940. for shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1941. self.sel_storage.insert(shape)
  1942. _, closest_shape = self.sel_storage.nearest(pos)
  1943. # constrain selection to happen only within a certain bounding box
  1944. x_coord, y_coord = closest_shape.geo[0].xy
  1945. delta = (x_coord[1] - x_coord[0])
  1946. # closest_shape_coords = (((x_coord[0] + delta / 2)), y_coord[0])
  1947. xmin = x_coord[0] - (0.7 * delta)
  1948. xmax = x_coord[0] + (1.7 * delta)
  1949. ymin = y_coord[0] - (0.7 * delta)
  1950. ymax = y_coord[0] + (1.7 * delta)
  1951. except StopIteration:
  1952. return ""
  1953. if pos[0] < xmin or pos[0] > xmax or pos[1] < ymin or pos[1] > ymax:
  1954. self.exc_editor_app.selected = []
  1955. else:
  1956. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  1957. if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Control':
  1958. # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  1959. # in the selected list, we removed it. Therefore first click selects, second deselects.
  1960. if key_modifier == Qt.ControlModifier:
  1961. if closest_shape in self.exc_editor_app.selected:
  1962. self.exc_editor_app.selected.remove(closest_shape)
  1963. else:
  1964. self.exc_editor_app.selected.append(closest_shape)
  1965. else:
  1966. self.exc_editor_app.selected = []
  1967. self.exc_editor_app.selected.append(closest_shape)
  1968. else:
  1969. if key_modifier == Qt.ShiftModifier:
  1970. if closest_shape in self.exc_editor_app.selected:
  1971. self.exc_editor_app.selected.remove(closest_shape)
  1972. else:
  1973. self.exc_editor_app.selected.append(closest_shape)
  1974. else:
  1975. self.exc_editor_app.selected = []
  1976. self.exc_editor_app.selected.append(closest_shape)
  1977. # select the diameter of the selected shape in the tool table
  1978. for storage in self.exc_editor_app.storage_dict:
  1979. for shape_s in self.exc_editor_app.selected:
  1980. if shape_s in self.exc_editor_app.storage_dict[storage].get_objects():
  1981. for key in self.exc_editor_app.tool2tooldia:
  1982. if self.exc_editor_app.tool2tooldia[key] == storage:
  1983. item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  1984. self.exc_editor_app.tools_table_exc.setCurrentItem(item)
  1985. # item.setSelected(True)
  1986. # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  1987. # midx = self.exc_editor_app.tools_table_exc.model().index((key - 1), 0)
  1988. # self.exc_editor_app.tools_table_exc.setCurrentIndex(midx)
  1989. self.draw_app.last_tool_selected = key
  1990. # delete whatever is in selection storage, there is no longer need for those shapes
  1991. self.sel_storage = FlatCAMExcEditor.make_storage()
  1992. return ""
  1993. # pos[0] and pos[1] are the mouse click coordinates (x, y)
  1994. # for storage in self.exc_editor_app.storage_dict:
  1995. # for obj_shape in self.exc_editor_app.storage_dict[storage].get_objects():
  1996. # minx, miny, maxx, maxy = obj_shape.geo.bounds
  1997. # if (minx <= pos[0] <= maxx) and (miny <= pos[1] <= maxy):
  1998. # over_shape_list.append(obj_shape)
  1999. #
  2000. # try:
  2001. # # if there is no shape under our click then deselect all shapes
  2002. # if not over_shape_list:
  2003. # self.exc_editor_app.selected = []
  2004. # FlatCAMExcEditor.draw_shape_idx = -1
  2005. # self.exc_editor_app.tools_table_exc.clearSelection()
  2006. # else:
  2007. # # if there are shapes under our click then advance through the list of them, one at the time in a
  2008. # # circular way
  2009. # FlatCAMExcEditor.draw_shape_idx = (FlatCAMExcEditor.draw_shape_idx + 1) % len(over_shape_list)
  2010. # obj_to_add = over_shape_list[int(FlatCAMExcEditor.draw_shape_idx)]
  2011. #
  2012. # if self.exc_editor_app.app.defaults["global_mselect_key"] == 'Shift':
  2013. # if self.exc_editor_app.modifiers == Qt.ShiftModifier:
  2014. # if obj_to_add in self.exc_editor_app.selected:
  2015. # self.exc_editor_app.selected.remove(obj_to_add)
  2016. # else:
  2017. # self.exc_editor_app.selected.append(obj_to_add)
  2018. # else:
  2019. # self.exc_editor_app.selected = []
  2020. # self.exc_editor_app.selected.append(obj_to_add)
  2021. # else:
  2022. # # if CONTROL key is pressed then we add to the selected list the current shape but if it's already
  2023. # # in the selected list, we removed it. Therefore first click selects, second deselects.
  2024. # if self.exc_editor_app.modifiers == Qt.ControlModifier:
  2025. # if obj_to_add in self.exc_editor_app.selected:
  2026. # self.exc_editor_app.selected.remove(obj_to_add)
  2027. # else:
  2028. # self.exc_editor_app.selected.append(obj_to_add)
  2029. # else:
  2030. # self.exc_editor_app.selected = []
  2031. # self.exc_editor_app.selected.append(obj_to_add)
  2032. #
  2033. # for storage in self.exc_editor_app.storage_dict:
  2034. # for shape in self.exc_editor_app.selected:
  2035. # if shape in self.exc_editor_app.storage_dict[storage].get_objects():
  2036. # for key in self.exc_editor_app.tool2tooldia:
  2037. # if self.exc_editor_app.tool2tooldia[key] == storage:
  2038. # item = self.exc_editor_app.tools_table_exc.item((key - 1), 1)
  2039. # item.setSelected(True)
  2040. # # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  2041. #
  2042. # except Exception as e:
  2043. # log.error("[ERROR] Something went bad. %s" % str(e))
  2044. # raise
  2045. class FCMove(FCShapeTool):
  2046. def __init__(self, draw_app):
  2047. FCShapeTool.__init__(self, draw_app)
  2048. self.name = 'move'
  2049. # self.shape_buffer = self.draw_app.shape_buffer
  2050. if not self.draw_app.selected:
  2051. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  2052. return
  2053. self.origin = None
  2054. self.destination = None
  2055. self.start_msg = _("Click on reference point.")
  2056. def set_origin(self, origin):
  2057. self.draw_app.app.inform.emit(_("Click on destination point."))
  2058. self.origin = origin
  2059. def click(self, point):
  2060. if len(self.draw_app.get_selected()) == 0:
  2061. return "Nothing to move."
  2062. if self.origin is None:
  2063. self.set_origin(point)
  2064. return "Click on final location."
  2065. else:
  2066. self.destination = point
  2067. self.make()
  2068. return "Done."
  2069. def make(self):
  2070. # Create new geometry
  2071. dx = self.destination[0] - self.origin[0]
  2072. dy = self.destination[1] - self.origin[1]
  2073. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2074. for geom in self.draw_app.get_selected()]
  2075. # Delete old
  2076. self.draw_app.delete_selected()
  2077. # # Select the new
  2078. # for g in self.geometry:
  2079. # # Note that g is not in the app's buffer yet!
  2080. # self.draw_app.set_selected(g)
  2081. self.complete = True
  2082. self.draw_app.app.inform.emit(_("[success]Done. Geometry(s) Move completed."))
  2083. def utility_geometry(self, data=None):
  2084. """
  2085. Temporary geometry on screen while using this tool.
  2086. :param data:
  2087. :return:
  2088. """
  2089. geo_list = []
  2090. if self.origin is None:
  2091. return None
  2092. if len(self.draw_app.get_selected()) == 0:
  2093. return None
  2094. dx = data[0] - self.origin[0]
  2095. dy = data[1] - self.origin[1]
  2096. try:
  2097. for geom in self.draw_app.get_selected():
  2098. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2099. except AttributeError:
  2100. self.draw_app.select_tool('select')
  2101. self.draw_app.selected = []
  2102. return
  2103. return DrawToolUtilityShape(geo_list)
  2104. # return DrawToolUtilityShape([affinity.translate(geom.geo, xoff=dx, yoff=dy)
  2105. # for geom in self.draw_app.get_selected()])
  2106. class FCCopy(FCMove):
  2107. def __init__(self, draw_app):
  2108. FCMove.__init__(self, draw_app)
  2109. self.name = 'copy'
  2110. def make(self):
  2111. # Create new geometry
  2112. dx = self.destination[0] - self.origin[0]
  2113. dy = self.destination[1] - self.origin[1]
  2114. self.geometry = [DrawToolShape(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2115. for geom in self.draw_app.get_selected()]
  2116. self.complete = True
  2117. self.draw_app.app.inform.emit(_("[success]Done. Geometry(s) Copy completed."))
  2118. class FCText(FCShapeTool):
  2119. def __init__(self, draw_app):
  2120. FCShapeTool.__init__(self, draw_app)
  2121. self.name = 'text'
  2122. # self.shape_buffer = self.draw_app.shape_buffer
  2123. self.draw_app = draw_app
  2124. self.app = draw_app.app
  2125. self.start_msg = _("Click on the Destination point...")
  2126. self.origin = (0, 0)
  2127. self.text_gui = TextInputTool(self.app)
  2128. self.text_gui.run()
  2129. def click(self, point):
  2130. # Create new geometry
  2131. dx = point[0]
  2132. dy = point[1]
  2133. try:
  2134. self.geometry = DrawToolShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2135. except Exception as e:
  2136. log.debug("Font geometry is empty or incorrect: %s" % str(e))
  2137. self.draw_app.app.inform.emit(_("[ERROR]Font not supported. Only Regular, Bold, Italic and BoldItalic are "
  2138. "supported. Error: %s") % str(e))
  2139. self.text_gui.text_path = []
  2140. self.text_gui.hide_tool()
  2141. self.draw_app.select_tool('select')
  2142. return
  2143. self.text_gui.text_path = []
  2144. self.text_gui.hide_tool()
  2145. self.complete = True
  2146. self.draw_app.app.inform.emit(_("[success]Done. Adding Text completed."))
  2147. def utility_geometry(self, data=None):
  2148. """
  2149. Temporary geometry on screen while using this tool.
  2150. :param data: mouse position coords
  2151. :return:
  2152. """
  2153. dx = data[0] - self.origin[0]
  2154. dy = data[1] - self.origin[1]
  2155. try:
  2156. return DrawToolUtilityShape(affinity.translate(self.text_gui.text_path, xoff=dx, yoff=dy))
  2157. except:
  2158. return
  2159. class FCBuffer(FCShapeTool):
  2160. def __init__(self, draw_app):
  2161. FCShapeTool.__init__(self, draw_app)
  2162. self.name = 'buffer'
  2163. # self.shape_buffer = self.draw_app.shape_buffer
  2164. self.draw_app = draw_app
  2165. self.app = draw_app.app
  2166. self.start_msg = _("Create buffer geometry ...")
  2167. self.origin = (0, 0)
  2168. self.buff_tool = BufferSelectionTool(self.app, self.draw_app)
  2169. self.buff_tool.run()
  2170. self.app.ui.notebook.setTabText(2, _("Buffer Tool"))
  2171. if self.draw_app.app.ui.splitter.sizes()[0] == 0:
  2172. self.draw_app.app.ui.splitter.setSizes([1, 1])
  2173. self.activate()
  2174. def on_buffer(self):
  2175. if not self.draw_app.selected:
  2176. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2177. return
  2178. try:
  2179. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2180. except ValueError:
  2181. # try to convert comma to decimal point. if it's still not working error message and return
  2182. try:
  2183. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2184. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2185. except ValueError:
  2186. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2187. "Add it and retry."))
  2188. return
  2189. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2190. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2191. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2192. self.draw_app.buffer(buffer_distance, join_style)
  2193. self.app.ui.notebook.setTabText(2, _("Tools"))
  2194. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2195. self.disactivate()
  2196. self.draw_app.app.inform.emit(_("[success]Done. Buffer Tool completed."))
  2197. def on_buffer_int(self):
  2198. if not self.draw_app.selected:
  2199. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2200. return
  2201. try:
  2202. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2203. except ValueError:
  2204. # try to convert comma to decimal point. if it's still not working error message and return
  2205. try:
  2206. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2207. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2208. except ValueError:
  2209. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2210. "Add it and retry."))
  2211. return
  2212. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2213. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2214. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2215. self.draw_app.buffer_int(buffer_distance, join_style)
  2216. self.app.ui.notebook.setTabText(2, _("Tools"))
  2217. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2218. self.disactivate()
  2219. self.draw_app.app.inform.emit(_("[success]Done. Buffer Int Tool completed."))
  2220. def on_buffer_ext(self):
  2221. if not self.draw_app.selected:
  2222. self.app.inform.emit(_("[WARNING_NOTCL] Buffer cancelled. No shape selected."))
  2223. return
  2224. try:
  2225. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value())
  2226. except ValueError:
  2227. # try to convert comma to decimal point. if it's still not working error message and return
  2228. try:
  2229. buffer_distance = float(self.buff_tool.buffer_distance_entry.get_value().replace(',', '.'))
  2230. self.buff_tool.buffer_distance_entry.set_value(buffer_distance)
  2231. except ValueError:
  2232. self.app.inform.emit(_("[WARNING_NOTCL] Buffer distance value is missing or wrong format. "
  2233. "Add it and retry."))
  2234. return
  2235. # the cb index start from 0 but the join styles for the buffer start from 1 therefore the adjustment
  2236. # I populated the combobox such that the index coincide with the join styles value (whcih is really an INT)
  2237. join_style = self.buff_tool.buffer_corner_cb.currentIndex() + 1
  2238. self.draw_app.buffer_ext(buffer_distance, join_style)
  2239. self.app.ui.notebook.setTabText(2, _("Tools"))
  2240. self.draw_app.app.ui.splitter.setSizes([0, 1])
  2241. self.disactivate()
  2242. self.draw_app.app.inform.emit(_("[success]Done. Buffer Ext Tool completed."))
  2243. def activate(self):
  2244. self.buff_tool.buffer_button.clicked.disconnect()
  2245. self.buff_tool.buffer_int_button.clicked.disconnect()
  2246. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2247. self.buff_tool.buffer_button.clicked.connect(self.on_buffer)
  2248. self.buff_tool.buffer_int_button.clicked.connect(self.on_buffer_int)
  2249. self.buff_tool.buffer_ext_button.clicked.connect(self.on_buffer_ext)
  2250. def disactivate(self):
  2251. self.buff_tool.buffer_button.clicked.disconnect()
  2252. self.buff_tool.buffer_int_button.clicked.disconnect()
  2253. self.buff_tool.buffer_ext_button.clicked.disconnect()
  2254. self.buff_tool.buffer_button.clicked.connect(self.buff_tool.on_buffer)
  2255. self.buff_tool.buffer_int_button.clicked.connect(self.buff_tool.on_buffer_int)
  2256. self.buff_tool.buffer_ext_button.clicked.connect(self.buff_tool.on_buffer_ext)
  2257. self.complete = True
  2258. self.draw_app.select_tool("select")
  2259. self.buff_tool.hide_tool()
  2260. class FCPaint(FCShapeTool):
  2261. def __init__(self, draw_app):
  2262. FCShapeTool.__init__(self, draw_app)
  2263. self.name = 'paint'
  2264. # self.shape_buffer = self.draw_app.shape_buffer
  2265. self.draw_app = draw_app
  2266. self.app = draw_app.app
  2267. self.start_msg = _("Create Paint geometry ...")
  2268. self.origin = (0, 0)
  2269. self.draw_app.paint_tool.run()
  2270. class FCTransform(FCShapeTool):
  2271. def __init__(self, draw_app):
  2272. FCShapeTool.__init__(self, draw_app)
  2273. self.name = 'transformation'
  2274. # self.shape_buffer = self.draw_app.shape_buffer
  2275. self.draw_app = draw_app
  2276. self.app = draw_app.app
  2277. self.start_msg = _("Shape transformations ...")
  2278. self.origin = (0, 0)
  2279. self.draw_app.transform_tool.run()
  2280. class FCDrillAdd(FCShapeTool):
  2281. """
  2282. Resulting type: MultiLineString
  2283. """
  2284. def __init__(self, draw_app):
  2285. DrawTool.__init__(self, draw_app)
  2286. self.name = 'drill_add'
  2287. self.selected_dia = None
  2288. try:
  2289. self.draw_app.app.inform.emit(self.start_msg)
  2290. # self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.tools_table_exc.currentRow() + 1]
  2291. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  2292. # as a visual marker, select again in tooltable the actual tool that we are using
  2293. # remember that it was deselected when clicking on canvas
  2294. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  2295. self.draw_app.tools_table_exc.setCurrentItem(item)
  2296. except KeyError:
  2297. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add a drill first select a tool"))
  2298. self.draw_app.select_tool("select")
  2299. return
  2300. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y))
  2301. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2302. self.draw_app.draw_utility_geometry(geo=geo)
  2303. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2304. # Switch notebook to Selected page
  2305. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2306. def click(self, point):
  2307. self.make()
  2308. return "Done."
  2309. def utility_geometry(self, data=None):
  2310. self.points = data
  2311. return DrawToolUtilityShape(self.util_shape(data))
  2312. def util_shape(self, point):
  2313. if point[0] is None and point[1] is None:
  2314. point_x = self.draw_app.x
  2315. point_y = self.draw_app.y
  2316. else:
  2317. point_x = point[0]
  2318. point_y = point[1]
  2319. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  2320. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  2321. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  2322. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  2323. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2324. def make(self):
  2325. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  2326. # to the value, as a list of itself
  2327. if self.selected_dia in self.draw_app.points_edit:
  2328. self.draw_app.points_edit[self.selected_dia].append(self.points)
  2329. else:
  2330. self.draw_app.points_edit[self.selected_dia] = [self.points]
  2331. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  2332. self.geometry = DrawToolShape(self.util_shape(self.points))
  2333. self.complete = True
  2334. self.draw_app.app.inform.emit(_("[success]Done. Drill added."))
  2335. class FCDrillArray(FCShapeTool):
  2336. """
  2337. Resulting type: MultiLineString
  2338. """
  2339. def __init__(self, draw_app):
  2340. DrawTool.__init__(self, draw_app)
  2341. self.name = 'drill_array'
  2342. self.draw_app.array_frame.show()
  2343. self.selected_dia = None
  2344. self.drill_axis = 'X'
  2345. self.drill_array = 'linear'
  2346. self.drill_array_size = None
  2347. self.drill_pitch = None
  2348. self.drill_linear_angle = None
  2349. self.drill_angle = None
  2350. self.drill_direction = None
  2351. self.drill_radius = None
  2352. self.origin = None
  2353. self.destination = None
  2354. self.flag_for_circ_array = None
  2355. self.last_dx = 0
  2356. self.last_dy = 0
  2357. self.pt = []
  2358. try:
  2359. self.draw_app.app.inform.emit(self.start_msg)
  2360. self.selected_dia = self.draw_app.tool2tooldia[self.draw_app.last_tool_selected]
  2361. # as a visual marker, select again in tooltable the actual tool that we are using
  2362. # remember that it was deselected when clicking on canvas
  2363. item = self.draw_app.tools_table_exc.item((self.draw_app.last_tool_selected - 1), 1)
  2364. self.draw_app.tools_table_exc.setCurrentItem(item)
  2365. except KeyError:
  2366. self.draw_app.app.inform.emit(_("[WARNING_NOTCL] To add an Drill Array first select a tool in Tool Table"))
  2367. return
  2368. geo = self.utility_geometry(data=(self.draw_app.snap_x, self.draw_app.snap_y), static=True)
  2369. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  2370. self.draw_app.draw_utility_geometry(geo=geo)
  2371. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2372. # Switch notebook to Selected page
  2373. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2374. def click(self, point):
  2375. if self.drill_array == 'Linear':
  2376. self.make()
  2377. return
  2378. else:
  2379. if self.flag_for_circ_array is None:
  2380. self.draw_app.in_action = True
  2381. self.pt.append(point)
  2382. self.flag_for_circ_array = True
  2383. self.set_origin(point)
  2384. self.draw_app.app.inform.emit(_("Click on the Drill Circular Array Start position"))
  2385. else:
  2386. self.destination = point
  2387. self.make()
  2388. self.flag_for_circ_array = None
  2389. return
  2390. def set_origin(self, origin):
  2391. self.origin = origin
  2392. def utility_geometry(self, data=None, static=None):
  2393. self.drill_axis = self.draw_app.drill_axis_radio.get_value()
  2394. self.drill_direction = self.draw_app.drill_direction_radio.get_value()
  2395. self.drill_array = self.draw_app.array_type_combo.get_value()
  2396. try:
  2397. self.drill_array_size = int(self.draw_app.drill_array_size_entry.get_value())
  2398. try:
  2399. self.drill_pitch = float(self.draw_app.drill_pitch_entry.get_value())
  2400. self.drill_linear_angle = float(self.draw_app.linear_angle_spinner.get_value())
  2401. self.drill_angle = float(self.draw_app.drill_angle_entry.get_value())
  2402. except TypeError:
  2403. self.draw_app.app.inform.emit(
  2404. _("[ERROR_NOTCL] The value is not Float. Check for comma instead of dot separator."))
  2405. return
  2406. except Exception as e:
  2407. self.draw_app.app.inform.emit(_("[ERROR_NOTCL] The value is mistyped. Check the value."))
  2408. return
  2409. if self.drill_array == 'Linear':
  2410. if data[0] is None and data[1] is None:
  2411. dx = self.draw_app.x
  2412. dy = self.draw_app.y
  2413. else:
  2414. dx = data[0]
  2415. dy = data[1]
  2416. geo_list = []
  2417. geo = None
  2418. self.points = [dx, dy]
  2419. for item in range(self.drill_array_size):
  2420. if self.drill_axis == 'X':
  2421. geo = self.util_shape(((dx + (self.drill_pitch * item)), dy))
  2422. if self.drill_axis == 'Y':
  2423. geo = self.util_shape((dx, (dy + (self.drill_pitch * item))))
  2424. if self.drill_axis == 'A':
  2425. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  2426. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  2427. geo = self.util_shape(
  2428. ((dx + (x_adj * item)), (dy + (y_adj * item)))
  2429. )
  2430. if static is None or static is False:
  2431. geo_list.append(affinity.translate(geo, xoff=(dx - self.last_dx), yoff=(dy - self.last_dy)))
  2432. else:
  2433. geo_list.append(geo)
  2434. # self.origin = data
  2435. self.last_dx = dx
  2436. self.last_dy = dy
  2437. return DrawToolUtilityShape(geo_list)
  2438. else:
  2439. if data[0] is None and data[1] is None:
  2440. cdx = self.draw_app.x
  2441. cdy = self.draw_app.y
  2442. else:
  2443. cdx = data[0]
  2444. cdy = data[1]
  2445. if len(self.pt) > 0:
  2446. temp_points = [x for x in self.pt]
  2447. temp_points.append([cdx, cdy])
  2448. return DrawToolUtilityShape(LineString(temp_points))
  2449. def util_shape(self, point):
  2450. if point[0] is None and point[1] is None:
  2451. point_x = self.draw_app.x
  2452. point_y = self.draw_app.y
  2453. else:
  2454. point_x = point[0]
  2455. point_y = point[1]
  2456. start_hor_line = ((point_x - (self.selected_dia / 2)), point_y)
  2457. stop_hor_line = ((point_x + (self.selected_dia / 2)), point_y)
  2458. start_vert_line = (point_x, (point_y - (self.selected_dia / 2)))
  2459. stop_vert_line = (point_x, (point_y + (self.selected_dia / 2)))
  2460. return MultiLineString([(start_hor_line, stop_hor_line), (start_vert_line, stop_vert_line)])
  2461. def make(self):
  2462. self.geometry = []
  2463. geo = None
  2464. # add the point to drills if the diameter is a key in the dict, if not, create it add the drill location
  2465. # to the value, as a list of itself
  2466. if self.selected_dia not in self.draw_app.points_edit:
  2467. self.draw_app.points_edit[self.selected_dia] = []
  2468. for i in range(self.drill_array_size):
  2469. self.draw_app.points_edit[self.selected_dia].append(self.points)
  2470. self.draw_app.current_storage = self.draw_app.storage_dict[self.selected_dia]
  2471. if self.drill_array == 'Linear':
  2472. for item in range(self.drill_array_size):
  2473. if self.drill_axis == 'X':
  2474. geo = self.util_shape(((self.points[0] + (self.drill_pitch * item)), self.points[1]))
  2475. if self.drill_axis == 'Y':
  2476. geo = self.util_shape((self.points[0], (self.points[1] + (self.drill_pitch * item))))
  2477. if self.drill_axis == 'A':
  2478. x_adj = self.drill_pitch * math.cos(math.radians(self.drill_linear_angle))
  2479. y_adj = self.drill_pitch * math.sin(math.radians(self.drill_linear_angle))
  2480. geo = self.util_shape(
  2481. ((self.points[0] + (x_adj * item)), (self.points[1] + (y_adj * item)))
  2482. )
  2483. self.geometry.append(DrawToolShape(geo))
  2484. else:
  2485. if (self.drill_angle * self.drill_array_size) > 360:
  2486. self.draw_app.app.inform.emit(_("[WARNING_NOTCL]Too many drills for the selected spacing angle."))
  2487. return
  2488. radius = distance(self.destination, self.origin)
  2489. initial_angle = math.asin((self.destination[1] - self.origin[1]) / radius)
  2490. for i in range(self.drill_array_size):
  2491. angle_radians = math.radians(self.drill_angle * i)
  2492. if self.drill_direction == 'CW':
  2493. x = self.origin[0] + radius * math.cos(-angle_radians + initial_angle)
  2494. y = self.origin[1] + radius * math.sin(-angle_radians + initial_angle)
  2495. else:
  2496. x = self.origin[0] + radius * math.cos(angle_radians + initial_angle)
  2497. y = self.origin[1] + radius * math.sin(angle_radians + initial_angle)
  2498. geo = self.util_shape((x, y))
  2499. self.geometry.append(DrawToolShape(geo))
  2500. self.complete = True
  2501. self.draw_app.app.inform.emit(_("[success]Done. Drill Array added."))
  2502. self.draw_app.in_action = True
  2503. self.draw_app.array_frame.hide()
  2504. return
  2505. class FCDrillResize(FCShapeTool):
  2506. def __init__(self, draw_app):
  2507. DrawTool.__init__(self, draw_app)
  2508. self.name = 'drill_resize'
  2509. self.draw_app.app.inform.emit(_("Click on the Drill(s) to resize ..."))
  2510. self.resize_dia = None
  2511. self.draw_app.resize_frame.show()
  2512. self.points = None
  2513. self.selected_dia_list = []
  2514. self.current_storage = None
  2515. self.geometry = []
  2516. self.destination_storage = None
  2517. self.draw_app.resize_btn.clicked.connect(self.make)
  2518. # Switch notebook to Selected page
  2519. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2520. def make(self):
  2521. self.draw_app.is_modified = True
  2522. try:
  2523. new_dia = self.draw_app.resdrill_entry.get_value()
  2524. except:
  2525. self.draw_app.app.inform.emit(_("[ERROR_NOTCL]Resize drill(s) failed. Please enter a diameter for resize."))
  2526. return
  2527. if new_dia not in self.draw_app.olddia_newdia:
  2528. self.destination_storage = FlatCAMGeoEditor.make_storage()
  2529. self.draw_app.storage_dict[new_dia] = self.destination_storage
  2530. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  2531. # each time a tool diameter is edited or added
  2532. self.draw_app.olddia_newdia[new_dia] = new_dia
  2533. else:
  2534. self.destination_storage = self.draw_app.storage_dict[new_dia]
  2535. for index in self.draw_app.tools_table_exc.selectedIndexes():
  2536. row = index.row()
  2537. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  2538. # therefore below we convert to float
  2539. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  2540. self.selected_dia_list.append(float(dia_on_row))
  2541. # since we add a new tool, we update also the intial state of the tool_table through it's dictionary
  2542. # we add a new entry in the tool2tooldia dict
  2543. self.draw_app.tool2tooldia[len(self.draw_app.olddia_newdia)] = new_dia
  2544. sel_shapes_to_be_deleted = []
  2545. for sel_dia in self.selected_dia_list:
  2546. self.current_storage = self.draw_app.storage_dict[sel_dia]
  2547. for select_shape in self.draw_app.get_selected():
  2548. if select_shape in self.current_storage.get_objects():
  2549. factor = new_dia / sel_dia
  2550. self.geometry.append(
  2551. DrawToolShape(affinity.scale(select_shape.geo, xfact=factor, yfact=factor, origin='center'))
  2552. )
  2553. self.current_storage.remove(select_shape)
  2554. # a hack to make the tool_table display less drills per diameter when shape(drill) is deleted
  2555. # self.points_edit it's only useful first time when we load the data into the storage
  2556. # but is still used as reference when building tool_table in self.build_ui()
  2557. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2558. # deleting self.points_edit elements (doesn't matter who but just the number)
  2559. # solved the display issue.
  2560. del self.draw_app.points_edit[sel_dia][0]
  2561. sel_shapes_to_be_deleted.append(select_shape)
  2562. self.draw_app.on_exc_shape_complete(self.destination_storage)
  2563. # a hack to make the tool_table display more drills per diameter when shape(drill) is added
  2564. # self.points_edit it's only useful first time when we load the data into the storage
  2565. # but is still used as reference when building tool_table in self.build_ui()
  2566. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  2567. # deleting self.points_edit elements (doesn't matter who but just the number)
  2568. # solved the display issue.
  2569. if new_dia not in self.draw_app.points_edit:
  2570. self.draw_app.points_edit[new_dia] = [(0, 0)]
  2571. else:
  2572. self.draw_app.points_edit[new_dia].append((0,0))
  2573. self.geometry = []
  2574. # if following the resize of the drills there will be no more drills for the selected tool then
  2575. # delete that tool
  2576. if not self.draw_app.points_edit[sel_dia]:
  2577. self.draw_app.on_tool_delete(sel_dia)
  2578. for shp in sel_shapes_to_be_deleted:
  2579. self.draw_app.selected.remove(shp)
  2580. sel_shapes_to_be_deleted = []
  2581. self.draw_app.build_ui()
  2582. self.draw_app.replot()
  2583. self.draw_app.resize_frame.hide()
  2584. self.complete = True
  2585. self.draw_app.app.inform.emit(_("[success]Done. Drill Resize completed."))
  2586. # MS: always return to the Select Tool
  2587. self.draw_app.select_tool("select")
  2588. class FCDrillMove(FCShapeTool):
  2589. def __init__(self, draw_app):
  2590. DrawTool.__init__(self, draw_app)
  2591. self.name = 'drill_move'
  2592. # self.shape_buffer = self.draw_app.shape_buffer
  2593. self.origin = None
  2594. self.destination = None
  2595. self.selected_dia_list = []
  2596. if self.draw_app.launched_from_shortcuts is True:
  2597. self.draw_app.launched_from_shortcuts = False
  2598. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2599. else:
  2600. self.draw_app.app.inform.emit(_("Click on reference location ..."))
  2601. self.current_storage = None
  2602. self.geometry = []
  2603. for index in self.draw_app.tools_table_exc.selectedIndexes():
  2604. row = index.row()
  2605. # on column 1 in tool tables we hold the diameters, and we retrieve them as strings
  2606. # therefore below we convert to float
  2607. dia_on_row = self.draw_app.tools_table_exc.item(row, 1).text()
  2608. self.selected_dia_list.append(float(dia_on_row))
  2609. # Switch notebook to Selected page
  2610. self.draw_app.app.ui.notebook.setCurrentWidget(self.draw_app.app.ui.selected_tab)
  2611. def set_origin(self, origin):
  2612. self.origin = origin
  2613. def click(self, point):
  2614. if len(self.draw_app.get_selected()) == 0:
  2615. return "Nothing to move."
  2616. if self.origin is None:
  2617. self.set_origin(point)
  2618. self.draw_app.app.inform.emit(_("Click on target location ..."))
  2619. return
  2620. else:
  2621. self.destination = point
  2622. self.make()
  2623. # MS: always return to the Select Tool
  2624. self.draw_app.select_tool("select")
  2625. return
  2626. def make(self):
  2627. # Create new geometry
  2628. dx = self.destination[0] - self.origin[0]
  2629. dy = self.destination[1] - self.origin[1]
  2630. sel_shapes_to_be_deleted = []
  2631. for sel_dia in self.selected_dia_list:
  2632. self.current_storage = self.draw_app.storage_dict[sel_dia]
  2633. for select_shape in self.draw_app.get_selected():
  2634. if select_shape in self.current_storage.get_objects():
  2635. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  2636. self.current_storage.remove(select_shape)
  2637. sel_shapes_to_be_deleted.append(select_shape)
  2638. self.draw_app.on_exc_shape_complete(self.current_storage)
  2639. self.geometry = []
  2640. for shp in sel_shapes_to_be_deleted:
  2641. self.draw_app.selected.remove(shp)
  2642. sel_shapes_to_be_deleted = []
  2643. self.draw_app.build_ui()
  2644. self.draw_app.app.inform.emit(_("[success]Done. Drill(s) Move completed."))
  2645. def utility_geometry(self, data=None):
  2646. """
  2647. Temporary geometry on screen while using this tool.
  2648. :param data:
  2649. :return:
  2650. """
  2651. geo_list = []
  2652. if self.origin is None:
  2653. return None
  2654. if len(self.draw_app.get_selected()) == 0:
  2655. return None
  2656. dx = data[0] - self.origin[0]
  2657. dy = data[1] - self.origin[1]
  2658. for geom in self.draw_app.get_selected():
  2659. geo_list.append(affinity.translate(geom.geo, xoff=dx, yoff=dy))
  2660. return DrawToolUtilityShape(geo_list)
  2661. class FCDrillCopy(FCDrillMove):
  2662. def __init__(self, draw_app):
  2663. FCDrillMove.__init__(self, draw_app)
  2664. self.name = 'drill_copy'
  2665. def make(self):
  2666. # Create new geometry
  2667. dx = self.destination[0] - self.origin[0]
  2668. dy = self.destination[1] - self.origin[1]
  2669. sel_shapes_to_be_deleted = []
  2670. for sel_dia in self.selected_dia_list:
  2671. self.current_storage = self.draw_app.storage_dict[sel_dia]
  2672. for select_shape in self.draw_app.get_selected():
  2673. if select_shape in self.current_storage.get_objects():
  2674. self.geometry.append(DrawToolShape(affinity.translate(select_shape.geo, xoff=dx, yoff=dy)))
  2675. # add some fake drills into the self.draw_app.points_edit to update the drill count in tool table
  2676. self.draw_app.points_edit[sel_dia].append((0, 0))
  2677. sel_shapes_to_be_deleted.append(select_shape)
  2678. self.draw_app.on_exc_shape_complete(self.current_storage)
  2679. self.geometry = []
  2680. for shp in sel_shapes_to_be_deleted:
  2681. self.draw_app.selected.remove(shp)
  2682. sel_shapes_to_be_deleted = []
  2683. self.draw_app.build_ui()
  2684. self.draw_app.app.inform.emit(_("[success]Done. Drill(s) copied."))
  2685. ########################
  2686. ### Main Application ###
  2687. ########################
  2688. class FlatCAMGeoEditor(QtCore.QObject):
  2689. transform_complete = QtCore.pyqtSignal()
  2690. draw_shape_idx = -1
  2691. def __init__(self, app, disabled=False):
  2692. assert isinstance(app, FlatCAMApp.App), \
  2693. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  2694. super(FlatCAMGeoEditor, self).__init__()
  2695. self.app = app
  2696. self.canvas = app.plotcanvas
  2697. self.app.ui.geo_add_circle_menuitem.triggered.connect(lambda: self.select_tool('circle'))
  2698. self.app.ui.geo_add_arc_menuitem.triggered.connect(lambda: self.select_tool('arc'))
  2699. self.app.ui.geo_add_rectangle_menuitem.triggered.connect(lambda: self.select_tool('rectangle'))
  2700. self.app.ui.geo_add_polygon_menuitem.triggered.connect(lambda: self.select_tool('polygon'))
  2701. self.app.ui.geo_add_path_menuitem.triggered.connect(lambda: self.select_tool('path'))
  2702. self.app.ui.geo_add_text_menuitem.triggered.connect(lambda: self.select_tool('text'))
  2703. self.app.ui.geo_paint_menuitem.triggered.connect(self.on_paint_tool)
  2704. self.app.ui.geo_buffer_menuitem.triggered.connect(self.on_buffer_tool)
  2705. self.app.ui.geo_transform_menuitem.triggered.connect(self.on_transform_tool)
  2706. self.app.ui.geo_delete_menuitem.triggered.connect(self.on_delete_btn)
  2707. self.app.ui.geo_union_menuitem.triggered.connect(self.union)
  2708. self.app.ui.geo_intersection_menuitem.triggered.connect(self.intersection)
  2709. self.app.ui.geo_subtract_menuitem.triggered.connect(self.subtract)
  2710. self.app.ui.geo_cutpath_menuitem.triggered.connect(self.cutpath)
  2711. self.app.ui.geo_copy_menuitem.triggered.connect(lambda: self.select_tool('copy'))
  2712. self.app.ui.geo_union_btn.triggered.connect(self.union)
  2713. self.app.ui.geo_intersection_btn.triggered.connect(self.intersection)
  2714. self.app.ui.geo_subtract_btn.triggered.connect(self.subtract)
  2715. self.app.ui.geo_cutpath_btn.triggered.connect(self.cutpath)
  2716. self.app.ui.geo_delete_btn.triggered.connect(self.on_delete_btn)
  2717. self.app.ui.geo_move_menuitem.triggered.connect(self.on_move)
  2718. self.app.ui.geo_cornersnap_menuitem.triggered.connect(self.on_corner_snap)
  2719. self.transform_complete.connect(self.on_transform_complete)
  2720. ## Toolbar events and properties
  2721. self.tools = {
  2722. "select": {"button": self.app.ui.geo_select_btn,
  2723. "constructor": FCSelect},
  2724. "arc": {"button": self.app.ui.geo_add_arc_btn,
  2725. "constructor": FCArc},
  2726. "circle": {"button": self.app.ui.geo_add_circle_btn,
  2727. "constructor": FCCircle},
  2728. "path": {"button": self.app.ui.geo_add_path_btn,
  2729. "constructor": FCPath},
  2730. "rectangle": {"button": self.app.ui.geo_add_rectangle_btn,
  2731. "constructor": FCRectangle},
  2732. "polygon": {"button": self.app.ui.geo_add_polygon_btn,
  2733. "constructor": FCPolygon},
  2734. "text": {"button": self.app.ui.geo_add_text_btn,
  2735. "constructor": FCText},
  2736. "buffer": {"button": self.app.ui.geo_add_buffer_btn,
  2737. "constructor": FCBuffer},
  2738. "paint": {"button": self.app.ui.geo_add_paint_btn,
  2739. "constructor": FCPaint},
  2740. "move": {"button": self.app.ui.geo_move_btn,
  2741. "constructor": FCMove},
  2742. "transform": {"button": self.app.ui.geo_transform_btn,
  2743. "constructor": FCTransform},
  2744. "copy": {"button": self.app.ui.geo_copy_btn,
  2745. "constructor": FCCopy}
  2746. }
  2747. ### Data
  2748. self.active_tool = None
  2749. self.storage = FlatCAMGeoEditor.make_storage()
  2750. self.utility = []
  2751. # VisPy visuals
  2752. self.fcgeometry = None
  2753. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  2754. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  2755. self.app.pool_recreated.connect(self.pool_recreated)
  2756. # Remove from scene
  2757. self.shapes.enabled = False
  2758. self.tool_shape.enabled = False
  2759. ## List of selected shapes.
  2760. self.selected = []
  2761. self.flat_geo = []
  2762. self.move_timer = QtCore.QTimer()
  2763. self.move_timer.setSingleShot(True)
  2764. # this var will store the state of the toolbar before starting the editor
  2765. self.toolbar_old_state = False
  2766. self.key = None # Currently pressed key
  2767. self.geo_key_modifiers = None
  2768. self.x = None # Current mouse cursor pos
  2769. self.y = None
  2770. # Current snapped mouse pos
  2771. self.snap_x = None
  2772. self.snap_y = None
  2773. self.pos = None
  2774. # signal that there is an action active like polygon or path
  2775. self.in_action = False
  2776. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  2777. self.launched_from_shortcuts = False
  2778. def make_callback(thetool):
  2779. def f():
  2780. self.on_tool_select(thetool)
  2781. return f
  2782. for tool in self.tools:
  2783. self.tools[tool]["button"].triggered.connect(make_callback(tool)) # Events
  2784. self.tools[tool]["button"].setCheckable(True) # Checkable
  2785. self.app.ui.grid_snap_btn.triggered.connect(self.on_grid_toggled)
  2786. self.app.ui.corner_snap_btn.setCheckable(True)
  2787. self.app.ui.corner_snap_btn.triggered.connect(lambda: self.toolbar_tool_toggle("corner_snap"))
  2788. self.options = {
  2789. "global_gridx": 0.1,
  2790. "global_gridy": 0.1,
  2791. "global_snap_max": 0.05,
  2792. "grid_snap": True,
  2793. "corner_snap": False,
  2794. "grid_gap_link": True
  2795. }
  2796. self.app.options_read_form()
  2797. for option in self.options:
  2798. if option in self.app.options:
  2799. self.options[option] = self.app.options[option]
  2800. self.app.ui.grid_gap_x_entry.setText(str(self.options["global_gridx"]))
  2801. self.app.ui.grid_gap_y_entry.setText(str(self.options["global_gridy"]))
  2802. self.app.ui.snap_max_dist_entry.setText(str(self.options["global_snap_max"]))
  2803. self.app.ui.grid_gap_link_cb.setChecked(True)
  2804. self.rtree_index = rtindex.Index()
  2805. def entry2option(option, entry):
  2806. try:
  2807. self.options[option] = float(entry.text())
  2808. except Exception as e:
  2809. log.debug("FlatCAMGeoEditor.__init__().entry2option() --> %s" % str(e))
  2810. return
  2811. def gridx_changed(goption, gentry):
  2812. entry2option(option=goption, entry=gentry)
  2813. # if the grid link is checked copy the value in the GridX field to GridY
  2814. if self.app.ui.grid_gap_link_cb.isChecked():
  2815. self.app.ui.grid_gap_y_entry.set_value(self.app.ui.grid_gap_x_entry.get_value())
  2816. self.app.ui.grid_gap_x_entry.setValidator(QtGui.QDoubleValidator())
  2817. self.app.ui.grid_gap_x_entry.textChanged.connect(
  2818. lambda: gridx_changed("global_gridx", self.app.ui.grid_gap_x_entry))
  2819. self.app.ui.grid_gap_y_entry.setValidator(QtGui.QDoubleValidator())
  2820. self.app.ui.grid_gap_y_entry.textChanged.connect(
  2821. lambda: entry2option("global_gridy", self.app.ui.grid_gap_y_entry))
  2822. self.app.ui.snap_max_dist_entry.setValidator(QtGui.QDoubleValidator())
  2823. self.app.ui.snap_max_dist_entry.textChanged.connect(
  2824. lambda: entry2option("snap_max", self.app.ui.snap_max_dist_entry))
  2825. # store the status of the editor so the Delete at object level will not work until the edit is finished
  2826. self.editor_active = False
  2827. # if using Paint store here the tool diameter used
  2828. self.paint_tooldia = None
  2829. self.paint_tool = PaintOptionsTool(self.app, self)
  2830. self.transform_tool = TransformEditorTool(self.app, self)
  2831. def pool_recreated(self, pool):
  2832. self.shapes.pool = pool
  2833. self.tool_shape.pool = pool
  2834. def on_transform_complete(self):
  2835. self.delete_selected()
  2836. self.replot()
  2837. def activate(self):
  2838. self.connect_canvas_event_handlers()
  2839. self.shapes.enabled = True
  2840. self.tool_shape.enabled = True
  2841. self.app.app_cursor.enabled = True
  2842. self.app.ui.snap_max_dist_entry.setEnabled(True)
  2843. self.app.ui.corner_snap_btn.setEnabled(True)
  2844. self.app.ui.snap_magnet.setVisible(True)
  2845. self.app.ui.corner_snap_btn.setVisible(True)
  2846. self.app.ui.geo_editor_menu.setDisabled(False)
  2847. self.app.ui.geo_editor_menu.menuAction().setVisible(True)
  2848. self.app.ui.update_obj_btn.setEnabled(True)
  2849. self.app.ui.g_editor_cmenu.setEnabled(True)
  2850. self.app.ui.geo_edit_toolbar.setDisabled(False)
  2851. self.app.ui.geo_edit_toolbar.setVisible(True)
  2852. self.app.ui.snap_toolbar.setDisabled(False)
  2853. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  2854. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  2855. for w in sel_tab_widget_list:
  2856. w.setEnabled(False)
  2857. # Tell the App that the editor is active
  2858. self.editor_active = True
  2859. def deactivate(self):
  2860. self.disconnect_canvas_event_handlers()
  2861. self.clear()
  2862. self.app.ui.geo_edit_toolbar.setDisabled(True)
  2863. settings = QSettings("Open Source", "FlatCAM")
  2864. if settings.contains("layout"):
  2865. layout = settings.value('layout', type=str)
  2866. if layout == 'standard':
  2867. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2868. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2869. self.app.ui.corner_snap_btn.setEnabled(False)
  2870. self.app.ui.snap_magnet.setVisible(False)
  2871. self.app.ui.corner_snap_btn.setVisible(False)
  2872. elif layout == 'compact':
  2873. # self.app.ui.geo_edit_toolbar.setVisible(True)
  2874. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2875. self.app.ui.corner_snap_btn.setEnabled(False)
  2876. else:
  2877. # self.app.ui.geo_edit_toolbar.setVisible(False)
  2878. self.app.ui.snap_magnet.setVisible(False)
  2879. self.app.ui.corner_snap_btn.setVisible(False)
  2880. self.app.ui.snap_max_dist_entry.setEnabled(False)
  2881. self.app.ui.corner_snap_btn.setEnabled(False)
  2882. # set the Editor Toolbar visibility to what was before entering in the Editor
  2883. self.app.ui.geo_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  2884. else self.app.ui.geo_edit_toolbar.setVisible(True)
  2885. # Disable visuals
  2886. self.shapes.enabled = False
  2887. self.tool_shape.enabled = False
  2888. self.app.app_cursor.enabled = False
  2889. self.app.ui.geo_editor_menu.setDisabled(True)
  2890. self.app.ui.geo_editor_menu.menuAction().setVisible(False)
  2891. self.app.ui.update_obj_btn.setEnabled(False)
  2892. self.app.ui.g_editor_cmenu.setEnabled(False)
  2893. self.app.ui.e_editor_cmenu.setEnabled(False)
  2894. # Tell the app that the editor is no longer active
  2895. self.editor_active = False
  2896. # Show original geometry
  2897. if self.fcgeometry:
  2898. self.fcgeometry.visible = True
  2899. def connect_canvas_event_handlers(self):
  2900. ## Canvas events
  2901. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  2902. # but those from FlatCAMGeoEditor
  2903. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  2904. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  2905. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2906. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  2907. self.app.collection.view.clicked.disconnect()
  2908. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  2909. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  2910. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  2911. def disconnect_canvas_event_handlers(self):
  2912. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  2913. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  2914. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  2915. # we restore the key and mouse control to FlatCAMApp method
  2916. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  2917. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  2918. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  2919. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  2920. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  2921. def add_shape(self, shape):
  2922. """
  2923. Adds a shape to the shape storage.
  2924. :param shape: Shape to be added.
  2925. :type shape: DrawToolShape
  2926. :return: None
  2927. """
  2928. # List of DrawToolShape?
  2929. if isinstance(shape, list):
  2930. for subshape in shape:
  2931. self.add_shape(subshape)
  2932. return
  2933. assert isinstance(shape, DrawToolShape), \
  2934. "Expected a DrawToolShape, got %s" % type(shape)
  2935. assert shape.geo is not None, \
  2936. "Shape object has empty geometry (None)"
  2937. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  2938. not isinstance(shape.geo, list), \
  2939. "Shape objects has empty geometry ([])"
  2940. if isinstance(shape, DrawToolUtilityShape):
  2941. self.utility.append(shape)
  2942. else:
  2943. self.storage.insert(shape) # TODO: Check performance
  2944. def delete_utility_geometry(self):
  2945. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  2946. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  2947. for_deletion = [shape for shape in self.utility]
  2948. for shape in for_deletion:
  2949. self.delete_shape(shape)
  2950. self.tool_shape.clear(update=True)
  2951. self.tool_shape.redraw()
  2952. def cutpath(self):
  2953. selected = self.get_selected()
  2954. tools = selected[1:]
  2955. toolgeo = cascaded_union([shp.geo for shp in tools])
  2956. target = selected[0]
  2957. if type(target.geo) == Polygon:
  2958. for ring in poly2rings(target.geo):
  2959. self.add_shape(DrawToolShape(ring.difference(toolgeo)))
  2960. self.delete_shape(target)
  2961. elif type(target.geo) == LineString or type(target.geo) == LinearRing:
  2962. self.add_shape(DrawToolShape(target.geo.difference(toolgeo)))
  2963. self.delete_shape(target)
  2964. elif type(target.geo) == MultiLineString:
  2965. try:
  2966. for linestring in target.geo:
  2967. self.add_shape(DrawToolShape(linestring.difference(toolgeo)))
  2968. except:
  2969. self.app.log.warning("Current LinearString does not intersect the target")
  2970. self.delete_shape(target)
  2971. else:
  2972. self.app.log.warning("Not implemented. Object type: %s" % str(type(target.geo)))
  2973. self.replot()
  2974. def toolbar_tool_toggle(self, key):
  2975. self.options[key] = self.sender().isChecked()
  2976. if self.options[key] == True:
  2977. return 1
  2978. else:
  2979. return 0
  2980. def clear(self):
  2981. self.active_tool = None
  2982. # self.shape_buffer = []
  2983. self.selected = []
  2984. self.shapes.clear(update=True)
  2985. self.tool_shape.clear(update=True)
  2986. self.storage = FlatCAMGeoEditor.make_storage()
  2987. self.replot()
  2988. def edit_fcgeometry(self, fcgeometry):
  2989. """
  2990. Imports the geometry from the given FlatCAM Geometry object
  2991. into the editor.
  2992. :param fcgeometry: FlatCAMGeometry
  2993. :return: None
  2994. """
  2995. assert isinstance(fcgeometry, Geometry), \
  2996. "Expected a Geometry, got %s" % type(fcgeometry)
  2997. self.deactivate()
  2998. self.activate()
  2999. # Hide original geometry
  3000. self.fcgeometry = fcgeometry
  3001. fcgeometry.visible = False
  3002. # Set selection tolerance
  3003. DrawToolShape.tolerance = fcgeometry.drawing_tolerance * 10
  3004. self.select_tool("select")
  3005. # Link shapes into editor.
  3006. for shape in fcgeometry.flatten():
  3007. if shape is not None: # TODO: Make flatten never create a None
  3008. if type(shape) == Polygon:
  3009. self.add_shape(DrawToolShape(shape.exterior))
  3010. for inter in shape.interiors:
  3011. self.add_shape(DrawToolShape(inter))
  3012. else:
  3013. self.add_shape(DrawToolShape(shape))
  3014. self.replot()
  3015. # start with GRID toolbar activated
  3016. if self.app.ui.grid_snap_btn.isChecked() == False:
  3017. self.app.ui.grid_snap_btn.trigger()
  3018. def on_buffer_tool(self):
  3019. buff_tool = BufferSelectionTool(self.app, self)
  3020. buff_tool.run()
  3021. def on_paint_tool(self):
  3022. paint_tool = PaintOptionsTool(self.app, self)
  3023. paint_tool.run()
  3024. def on_transform_tool(self):
  3025. transform_tool = TransformEditorTool(self.app, self)
  3026. transform_tool.run()
  3027. def on_tool_select(self, tool):
  3028. """
  3029. Behavior of the toolbar. Tool initialization.
  3030. :rtype : None
  3031. """
  3032. self.app.log.debug("on_tool_select('%s')" % tool)
  3033. # This is to make the group behave as radio group
  3034. if tool in self.tools:
  3035. if self.tools[tool]["button"].isChecked():
  3036. self.app.log.debug("%s is checked." % tool)
  3037. for t in self.tools:
  3038. if t != tool:
  3039. self.tools[t]["button"].setChecked(False)
  3040. self.active_tool = self.tools[tool]["constructor"](self)
  3041. if not isinstance(self.active_tool, FCSelect):
  3042. self.app.inform.emit(self.active_tool.start_msg)
  3043. else:
  3044. self.app.log.debug("%s is NOT checked." % tool)
  3045. for t in self.tools:
  3046. self.tools[t]["button"].setChecked(False)
  3047. self.active_tool = None
  3048. def draw_tool_path(self):
  3049. self.select_tool('path')
  3050. return
  3051. def draw_tool_rectangle(self):
  3052. self.select_tool('rectangle')
  3053. return
  3054. def on_grid_toggled(self):
  3055. self.toolbar_tool_toggle("grid_snap")
  3056. # make sure that the cursor shape is enabled/disabled, too
  3057. if self.options['grid_snap'] is True:
  3058. self.app.app_cursor.enabled = True
  3059. else:
  3060. self.app.app_cursor.enabled = False
  3061. def on_canvas_click(self, event):
  3062. """
  3063. event.x and .y have canvas coordinates
  3064. event.xdaya and .ydata have plot coordinates
  3065. :param event: Event object dispatched by Matplotlib
  3066. :return: None
  3067. """
  3068. if event.button is 1:
  3069. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3070. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  3071. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  3072. ### Snap coordinates
  3073. x, y = self.snap(self.pos[0], self.pos[1])
  3074. self.pos = (x, y)
  3075. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3076. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3077. if modifiers == QtCore.Qt.ShiftModifier:
  3078. self.app.clipboard.setText(
  3079. self.app.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3080. return
  3081. # Selection with left mouse button
  3082. if self.active_tool is not None and event.button is 1:
  3083. # Dispatch event to active_tool
  3084. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3085. msg = self.active_tool.click(self.snap(self.pos[0], self.pos[1]))
  3086. # If it is a shape generating tool
  3087. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  3088. self.on_shape_complete()
  3089. # MS: always return to the Select Tool if modifier key is not pressed
  3090. # else return to the current tool
  3091. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3092. if self.app.defaults["global_mselect_key"] == 'Control':
  3093. modifier_to_use = Qt.ControlModifier
  3094. else:
  3095. modifier_to_use = Qt.ShiftModifier
  3096. # if modifier key is pressed then we add to the selected list the current shape but if
  3097. # it's already in the selected list, we removed it. Therefore first click selects, second deselects.
  3098. if key_modifier == modifier_to_use:
  3099. self.select_tool(self.active_tool.name)
  3100. else:
  3101. self.select_tool("select")
  3102. return
  3103. if isinstance(self.active_tool, FCSelect):
  3104. # self.app.log.debug("Replotting after click.")
  3105. self.replot()
  3106. else:
  3107. self.app.log.debug("No active tool to respond to click!")
  3108. def on_canvas_move(self, event):
  3109. """
  3110. Called on 'mouse_move' event
  3111. event.pos have canvas screen coordinates
  3112. :param event: Event object dispatched by VisPy SceneCavas
  3113. :return: None
  3114. """
  3115. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  3116. event.xdata, event.ydata = pos[0], pos[1]
  3117. self.x = event.xdata
  3118. self.y = event.ydata
  3119. # Prevent updates on pan
  3120. # if len(event.buttons) > 0:
  3121. # return
  3122. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3123. if event.button == 2:
  3124. self.app.panning_action = True
  3125. return
  3126. else:
  3127. self.app.panning_action = False
  3128. try:
  3129. x = float(event.xdata)
  3130. y = float(event.ydata)
  3131. except TypeError:
  3132. return
  3133. if self.active_tool is None:
  3134. return
  3135. ### Snap coordinates
  3136. x, y = self.snap(x, y)
  3137. self.snap_x = x
  3138. self.snap_y = y
  3139. # update the position label in the infobar since the APP mouse event handlers are disconnected
  3140. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3141. "<b>Y</b>: %.4f" % (x, y))
  3142. if self.pos is None:
  3143. self.pos = (0, 0)
  3144. dx = x - self.pos[0]
  3145. dy = y - self.pos[1]
  3146. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  3147. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3148. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3149. ### Utility geometry (animated)
  3150. geo = self.active_tool.utility_geometry(data=(x, y))
  3151. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  3152. # Remove any previous utility shape
  3153. self.tool_shape.clear(update=True)
  3154. self.draw_utility_geometry(geo=geo)
  3155. ### Selection area on canvas section ###
  3156. dx = pos[0] - self.pos[0]
  3157. if event.is_dragging == 1 and event.button == 1:
  3158. self.app.delete_selection_shape()
  3159. if dx < 0:
  3160. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  3161. color=self.app.defaults["global_alt_sel_line"],
  3162. face_color=self.app.defaults['global_alt_sel_fill'])
  3163. self.app.selection_type = False
  3164. else:
  3165. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  3166. self.app.selection_type = True
  3167. else:
  3168. self.app.selection_type = None
  3169. # Update cursor
  3170. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  3171. def on_canvas_click_release(self, event):
  3172. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  3173. if self.app.grid_status():
  3174. pos = self.snap(pos_canvas[0], pos_canvas[1])
  3175. else:
  3176. pos = (pos_canvas[0], pos_canvas[1])
  3177. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3178. # canvas menu
  3179. try:
  3180. if event.button == 2: # right click
  3181. if self.app.panning_action is True:
  3182. self.app.panning_action = False
  3183. else:
  3184. if self.in_action is False:
  3185. self.app.cursor = QtGui.QCursor()
  3186. self.app.ui.popMenu.popup(self.app.cursor.pos())
  3187. else:
  3188. # if right click on canvas and the active tool need to be finished (like Path or Polygon)
  3189. # right mouse click will finish the action
  3190. if isinstance(self.active_tool, FCShapeTool):
  3191. self.active_tool.click(self.snap(self.x, self.y))
  3192. self.active_tool.make()
  3193. if self.active_tool.complete:
  3194. self.on_shape_complete()
  3195. self.app.inform.emit(_("[success]Done."))
  3196. # MS: always return to the Select Tool if modifier key is not pressed
  3197. # else return to the current tool
  3198. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  3199. if self.app.defaults["global_mselect_key"] == 'Control':
  3200. modifier_to_use = Qt.ControlModifier
  3201. else:
  3202. modifier_to_use = Qt.ShiftModifier
  3203. if key_modifier == modifier_to_use:
  3204. self.select_tool(self.active_tool.name)
  3205. else:
  3206. self.select_tool("select")
  3207. except Exception as e:
  3208. log.warning("Error: %s" % str(e))
  3209. return
  3210. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3211. # selection and then select a type of selection ("enclosing" or "touching")
  3212. try:
  3213. if event.button == 1: # left click
  3214. if self.app.selection_type is not None:
  3215. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  3216. self.app.selection_type = None
  3217. elif isinstance(self.active_tool, FCSelect):
  3218. # Dispatch event to active_tool
  3219. # msg = self.active_tool.click(self.snap(event.xdata, event.ydata))
  3220. msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  3221. # self.app.inform.emit(msg)
  3222. self.replot()
  3223. except Exception as e:
  3224. log.warning("Error: %s" % str(e))
  3225. return
  3226. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  3227. """
  3228. :param start_pos: mouse position when the selection LMB click was done
  3229. :param end_pos: mouse position when the left mouse button is released
  3230. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3231. :type Bool
  3232. :return:
  3233. """
  3234. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3235. self.app.delete_selection_shape()
  3236. for obj in self.storage.get_objects():
  3237. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  3238. (sel_type is False and poly_selection.intersects(obj.geo)):
  3239. if self.key == self.app.defaults["global_mselect_key"]:
  3240. if obj in self.selected:
  3241. self.selected.remove(obj)
  3242. else:
  3243. # add the object to the selected shapes
  3244. self.selected.append(obj)
  3245. else:
  3246. if obj not in self.selected:
  3247. self.selected.append(obj)
  3248. self.replot()
  3249. def draw_utility_geometry(self, geo):
  3250. # Add the new utility shape
  3251. try:
  3252. # this case is for the Font Parse
  3253. for el in list(geo.geo):
  3254. if type(el) == MultiPolygon:
  3255. for poly in el:
  3256. self.tool_shape.add(
  3257. shape=poly,
  3258. color=(self.app.defaults["global_draw_color"] + '80'),
  3259. update=False,
  3260. layer=0,
  3261. tolerance=None
  3262. )
  3263. elif type(el) == MultiLineString:
  3264. for linestring in el:
  3265. self.tool_shape.add(
  3266. shape=linestring,
  3267. color=(self.app.defaults["global_draw_color"] + '80'),
  3268. update=False,
  3269. layer=0,
  3270. tolerance=None
  3271. )
  3272. else:
  3273. self.tool_shape.add(
  3274. shape=el,
  3275. color=(self.app.defaults["global_draw_color"] + '80'),
  3276. update=False,
  3277. layer=0,
  3278. tolerance=None
  3279. )
  3280. except TypeError:
  3281. self.tool_shape.add(
  3282. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  3283. update=False, layer=0, tolerance=None)
  3284. self.tool_shape.redraw()
  3285. def on_delete_btn(self):
  3286. self.delete_selected()
  3287. self.replot()
  3288. def delete_selected(self):
  3289. tempref = [s for s in self.selected]
  3290. for shape in tempref:
  3291. self.delete_shape(shape)
  3292. self.selected = []
  3293. def delete_shape(self, shape):
  3294. if shape in self.utility:
  3295. self.utility.remove(shape)
  3296. return
  3297. self.storage.remove(shape)
  3298. if shape in self.selected:
  3299. self.selected.remove(shape) # TODO: Check performance
  3300. def on_move(self):
  3301. self.app.ui.geo_move_btn.setChecked(True)
  3302. self.on_tool_select('move')
  3303. def on_move_click(self):
  3304. if not self.selected:
  3305. self.app.inform.emit(_("[WARNING_NOTCL] Move cancelled. No shape selected."))
  3306. return
  3307. self.on_move()
  3308. self.active_tool.set_origin(self.snap(self.x, self.y))
  3309. def on_copy_click(self):
  3310. if not self.selected:
  3311. self.app.inform.emit(_("[WARNING_NOTCL] Copy cancelled. No shape selected."))
  3312. return
  3313. self.app.ui.geo_copy_btn.setChecked(True)
  3314. self.app.geo_editor.on_tool_select('copy')
  3315. self.app.geo_editor.active_tool.set_origin(self.app.geo_editor.snap(
  3316. self.app.geo_editor.x, self.app.geo_editor.y))
  3317. self.app.inform.emit(_("Click on target point."))
  3318. def on_corner_snap(self):
  3319. self.app.ui.corner_snap_btn.trigger()
  3320. def get_selected(self):
  3321. """
  3322. Returns list of shapes that are selected in the editor.
  3323. :return: List of shapes.
  3324. """
  3325. # return [shape for shape in self.shape_buffer if shape["selected"]]
  3326. return self.selected
  3327. def plot_shape(self, geometry=None, color='black', linewidth=1):
  3328. """
  3329. Plots a geometric object or list of objects without rendering. Plotted objects
  3330. are returned as a list. This allows for efficient/animated rendering.
  3331. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  3332. :param color: Shape color
  3333. :param linewidth: Width of lines in # of pixels.
  3334. :return: List of plotted elements.
  3335. """
  3336. plot_elements = []
  3337. if geometry is None:
  3338. geometry = self.active_tool.geometry
  3339. try:
  3340. for geo in geometry:
  3341. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  3342. ## Non-iterable
  3343. except TypeError:
  3344. ## DrawToolShape
  3345. if isinstance(geometry, DrawToolShape):
  3346. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  3347. ## Polygon: Descend into exterior and each interior.
  3348. if type(geometry) == Polygon:
  3349. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  3350. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  3351. if type(geometry) == LineString or type(geometry) == LinearRing:
  3352. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0,
  3353. tolerance=self.fcgeometry.drawing_tolerance))
  3354. if type(geometry) == Point:
  3355. pass
  3356. return plot_elements
  3357. def plot_all(self):
  3358. """
  3359. Plots all shapes in the editor.
  3360. :return: None
  3361. :rtype: None
  3362. """
  3363. # self.app.log.debug("plot_all()")
  3364. self.shapes.clear(update=True)
  3365. for shape in self.storage.get_objects():
  3366. if shape.geo is None: # TODO: This shouldn't have happened
  3367. continue
  3368. if shape in self.selected:
  3369. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  3370. continue
  3371. self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  3372. for shape in self.utility:
  3373. self.plot_shape(geometry=shape.geo, linewidth=1)
  3374. continue
  3375. self.shapes.redraw()
  3376. def replot(self):
  3377. self.plot_all()
  3378. def on_shape_complete(self):
  3379. self.app.log.debug("on_shape_complete()")
  3380. # Add shape
  3381. self.add_shape(self.active_tool.geometry)
  3382. # Remove any utility shapes
  3383. self.delete_utility_geometry()
  3384. self.tool_shape.clear(update=True)
  3385. # Replot and reset tool.
  3386. self.replot()
  3387. # self.active_tool = type(self.active_tool)(self)
  3388. @staticmethod
  3389. def make_storage():
  3390. ## Shape storage.
  3391. storage = FlatCAMRTreeStorage()
  3392. storage.get_points = DrawToolShape.get_pts
  3393. return storage
  3394. def select_tool(self, toolname):
  3395. """
  3396. Selects a drawing tool. Impacts the object and GUI.
  3397. :param toolname: Name of the tool.
  3398. :return: None
  3399. """
  3400. self.tools[toolname]["button"].setChecked(True)
  3401. self.on_tool_select(toolname)
  3402. def set_selected(self, shape):
  3403. # Remove and add to the end.
  3404. if shape in self.selected:
  3405. self.selected.remove(shape)
  3406. self.selected.append(shape)
  3407. def set_unselected(self, shape):
  3408. if shape in self.selected:
  3409. self.selected.remove(shape)
  3410. def snap(self, x, y):
  3411. """
  3412. Adjusts coordinates to snap settings.
  3413. :param x: Input coordinate X
  3414. :param y: Input coordinate Y
  3415. :return: Snapped (x, y)
  3416. """
  3417. snap_x, snap_y = (x, y)
  3418. snap_distance = Inf
  3419. ### Object (corner?) snap
  3420. ### No need for the objects, just the coordinates
  3421. ### in the index.
  3422. if self.options["corner_snap"]:
  3423. try:
  3424. nearest_pt, shape = self.storage.nearest((x, y))
  3425. nearest_pt_distance = distance((x, y), nearest_pt)
  3426. if nearest_pt_distance <= float(self.options["global_snap_max"]):
  3427. snap_distance = nearest_pt_distance
  3428. snap_x, snap_y = nearest_pt
  3429. except (StopIteration, AssertionError):
  3430. pass
  3431. ### Grid snap
  3432. if self.options["grid_snap"]:
  3433. if self.options["global_gridx"] != 0:
  3434. snap_x_ = round(x / self.options["global_gridx"]) * self.options['global_gridx']
  3435. else:
  3436. snap_x_ = x
  3437. # If the Grid_gap_linked on Grid Toolbar is checked then the snap distance on GridY entry will be ignored
  3438. # and it will use the snap distance from GridX entry
  3439. if self.app.ui.grid_gap_link_cb.isChecked():
  3440. if self.options["global_gridx"] != 0:
  3441. snap_y_ = round(y / self.options["global_gridx"]) * self.options['global_gridx']
  3442. else:
  3443. snap_y_ = y
  3444. else:
  3445. if self.options["global_gridy"] != 0:
  3446. snap_y_ = round(y / self.options["global_gridy"]) * self.options['global_gridy']
  3447. else:
  3448. snap_y_ = y
  3449. nearest_grid_distance = distance((x, y), (snap_x_, snap_y_))
  3450. if nearest_grid_distance < snap_distance:
  3451. snap_x, snap_y = (snap_x_, snap_y_)
  3452. return snap_x, snap_y
  3453. def update_fcgeometry(self, fcgeometry):
  3454. """
  3455. Transfers the geometry tool shape buffer to the selected geometry
  3456. object. The geometry already in the object are removed.
  3457. :param fcgeometry: FlatCAMGeometry
  3458. :return: None
  3459. """
  3460. fcgeometry.solid_geometry = []
  3461. # for shape in self.shape_buffer:
  3462. for shape in self.storage.get_objects():
  3463. fcgeometry.solid_geometry.append(shape.geo)
  3464. # re-enable all the widgets in the Selected Tab that were disabled after entering in Edit Geometry Mode
  3465. sel_tab_widget_list = self.app.ui.selected_tab.findChildren(QtWidgets.QWidget)
  3466. for w in sel_tab_widget_list:
  3467. w.setEnabled(True)
  3468. def update_options(self, obj):
  3469. if self.paint_tooldia:
  3470. obj.options['cnctooldia'] = self.paint_tooldia
  3471. self.paint_tooldia = None
  3472. return True
  3473. else:
  3474. return False
  3475. def union(self):
  3476. """
  3477. Makes union of selected polygons. Original polygons
  3478. are deleted.
  3479. :return: None.
  3480. """
  3481. results = cascaded_union([t.geo for t in self.get_selected()])
  3482. # Delete originals.
  3483. for_deletion = [s for s in self.get_selected()]
  3484. for shape in for_deletion:
  3485. self.delete_shape(shape)
  3486. # Selected geometry is now gone!
  3487. self.selected = []
  3488. self.add_shape(DrawToolShape(results))
  3489. self.replot()
  3490. def intersection(self):
  3491. """
  3492. Makes intersectino of selected polygons. Original polygons are deleted.
  3493. :return: None
  3494. """
  3495. shapes = self.get_selected()
  3496. try:
  3497. results = shapes[0].geo
  3498. except Exception as e:
  3499. log.debug("FlatCAMGeoEditor.intersection() --> %s" % str(e))
  3500. self.app.inform.emit(_("[WARNING_NOTCL]A selection of at least 2 geo items is required to do Intersection."))
  3501. self.select_tool('select')
  3502. return
  3503. for shape in shapes[1:]:
  3504. results = results.intersection(shape.geo)
  3505. # Delete originals.
  3506. for_deletion = [s for s in self.get_selected()]
  3507. for shape in for_deletion:
  3508. self.delete_shape(shape)
  3509. # Selected geometry is now gone!
  3510. self.selected = []
  3511. self.add_shape(DrawToolShape(results))
  3512. self.replot()
  3513. def subtract(self):
  3514. selected = self.get_selected()
  3515. try:
  3516. tools = selected[1:]
  3517. toolgeo = cascaded_union([shp.geo for shp in tools])
  3518. result = selected[0].geo.difference(toolgeo)
  3519. self.delete_shape(selected[0])
  3520. self.add_shape(DrawToolShape(result))
  3521. self.replot()
  3522. except Exception as e:
  3523. log.debug(str(e))
  3524. def buffer(self, buf_distance, join_style):
  3525. selected = self.get_selected()
  3526. if buf_distance < 0:
  3527. self.app.inform.emit(
  3528. _( "[ERROR_NOTCL]Negative buffer value is not accepted. Use Buffer interior to generate an 'inside' shape"))
  3529. # deselect everything
  3530. self.selected = []
  3531. self.replot()
  3532. return
  3533. if len(selected) == 0:
  3534. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3535. return
  3536. if not isinstance(buf_distance, float):
  3537. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3538. # deselect everything
  3539. self.selected = []
  3540. self.replot()
  3541. return
  3542. pre_buffer = cascaded_union([t.geo for t in selected])
  3543. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3544. if results.is_empty:
  3545. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a different buffer value."))
  3546. # deselect everything
  3547. self.selected = []
  3548. self.replot()
  3549. return
  3550. self.add_shape(DrawToolShape(results))
  3551. self.replot()
  3552. self.app.inform.emit(_("[success]Full buffer geometry created."))
  3553. def buffer_int(self, buf_distance, join_style):
  3554. selected = self.get_selected()
  3555. if buf_distance < 0:
  3556. self.app.inform.emit(
  3557. _("[ERROR_NOTCL]Negative buffer value is not accepted. "
  3558. "Use Buffer interior to generate an 'inside' shape")
  3559. )
  3560. # deselect everything
  3561. self.selected = []
  3562. self.replot()
  3563. return
  3564. if len(selected) == 0:
  3565. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3566. return
  3567. if not isinstance(buf_distance, float):
  3568. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3569. # deselect everything
  3570. self.selected = []
  3571. self.replot()
  3572. return
  3573. pre_buffer = cascaded_union([t.geo for t in selected])
  3574. results = pre_buffer.buffer(-buf_distance + 1e-10, resolution=32, join_style=join_style)
  3575. if results.is_empty:
  3576. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a smaller buffer value."))
  3577. # deselect everything
  3578. self.selected = []
  3579. self.replot()
  3580. return
  3581. if type(results) == MultiPolygon:
  3582. for poly in results:
  3583. self.add_shape(DrawToolShape(poly.exterior))
  3584. else:
  3585. self.add_shape(DrawToolShape(results.exterior))
  3586. self.replot()
  3587. self.app.inform.emit(_("[success]Exterior buffer geometry created."))
  3588. # selected = self.get_selected()
  3589. #
  3590. # if len(selected) == 0:
  3591. # self.app.inform.emit("[WARNING] Nothing selected for buffering.")
  3592. # return
  3593. #
  3594. # if not isinstance(buf_distance, float):
  3595. # self.app.inform.emit("[WARNING] Invalid distance for buffering.")
  3596. # return
  3597. #
  3598. # pre_buffer = cascaded_union([t.geo for t in selected])
  3599. # results = pre_buffer.buffer(buf_distance)
  3600. # if results.is_empty:
  3601. # self.app.inform.emit("Failed. Choose a smaller buffer value.")
  3602. # return
  3603. #
  3604. # int_geo = []
  3605. # if type(results) == MultiPolygon:
  3606. # for poly in results:
  3607. # for g in poly.interiors:
  3608. # int_geo.append(g)
  3609. # res = cascaded_union(int_geo)
  3610. # self.add_shape(DrawToolShape(res))
  3611. # else:
  3612. # print(results.interiors)
  3613. # for g in results.interiors:
  3614. # int_geo.append(g)
  3615. # res = cascaded_union(int_geo)
  3616. # self.add_shape(DrawToolShape(res))
  3617. #
  3618. # self.replot()
  3619. # self.app.inform.emit("Interior buffer geometry created.")
  3620. def buffer_ext(self, buf_distance, join_style):
  3621. selected = self.get_selected()
  3622. if buf_distance < 0:
  3623. self.app.inform.emit(_("[ERROR_NOTCL]Negative buffer value is not accepted. "
  3624. "Use Buffer interior to generate an 'inside' shape"))
  3625. # deselect everything
  3626. self.selected = []
  3627. self.replot()
  3628. return
  3629. if len(selected) == 0:
  3630. self.app.inform.emit(_("[WARNING_NOTCL] Nothing selected for buffering."))
  3631. return
  3632. if not isinstance(buf_distance, float):
  3633. self.app.inform.emit(_("[WARNING_NOTCL] Invalid distance for buffering."))
  3634. # deselect everything
  3635. self.selected = []
  3636. self.replot()
  3637. return
  3638. pre_buffer = cascaded_union([t.geo for t in selected])
  3639. results = pre_buffer.buffer(buf_distance - 1e-10, resolution=32, join_style=join_style)
  3640. if results.is_empty:
  3641. self.app.inform.emit(_("[ERROR_NOTCL]Failed, the result is empty. Choose a different buffer value."))
  3642. # deselect everything
  3643. self.selected = []
  3644. self.replot()
  3645. return
  3646. if type(results) == MultiPolygon:
  3647. for poly in results:
  3648. self.add_shape(DrawToolShape(poly.exterior))
  3649. else:
  3650. self.add_shape(DrawToolShape(results.exterior))
  3651. self.replot()
  3652. self.app.inform.emit(_("[success]Exterior buffer geometry created."))
  3653. # def paint(self, tooldia, overlap, margin, method):
  3654. # selected = self.get_selected()
  3655. #
  3656. # if len(selected) == 0:
  3657. # self.app.inform.emit("[WARNING] Nothing selected for painting.")
  3658. # return
  3659. #
  3660. # for param in [tooldia, overlap, margin]:
  3661. # if not isinstance(param, float):
  3662. # param_name = [k for k, v in locals().items() if v is param][0]
  3663. # self.app.inform.emit("[WARNING] Invalid value for {}".format(param))
  3664. #
  3665. # # Todo: Check for valid method.
  3666. #
  3667. # # Todo: This is the 3rd implementation on painting polys... try to consolidate
  3668. #
  3669. # results = []
  3670. #
  3671. # def recurse(geo):
  3672. # try:
  3673. # for subg in geo:
  3674. # for subsubg in recurse(subg):
  3675. # yield subsubg
  3676. # except TypeError:
  3677. # if isinstance(geo, LinearRing):
  3678. # yield geo
  3679. #
  3680. # raise StopIteration
  3681. #
  3682. # for geo in selected:
  3683. # print(type(geo.geo))
  3684. #
  3685. # local_results = []
  3686. # for poly in recurse(geo.geo):
  3687. # if method == "seed":
  3688. # # Type(cp) == FlatCAMRTreeStorage | None
  3689. # cp = Geometry.clear_polygon2(poly.buffer(-margin),
  3690. # tooldia, overlap=overlap)
  3691. #
  3692. # else:
  3693. # # Type(cp) == FlatCAMRTreeStorage | None
  3694. # cp = Geometry.clear_polygon(poly.buffer(-margin),
  3695. # tooldia, overlap=overlap)
  3696. #
  3697. # if cp is not None:
  3698. # local_results += list(cp.get_objects())
  3699. #
  3700. # results.append(cascaded_union(local_results))
  3701. #
  3702. # # This is a dirty patch:
  3703. # for r in results:
  3704. # self.add_shape(DrawToolShape(r))
  3705. #
  3706. # self.replot()
  3707. def paint(self, tooldia, overlap, margin, connect, contour, method):
  3708. self.paint_tooldia = tooldia
  3709. selected = self.get_selected()
  3710. if len(selected) == 0:
  3711. self.app.inform.emit(_("[WARNING_NOTCL]Nothing selected for painting."))
  3712. return
  3713. for param in [tooldia, overlap, margin]:
  3714. if not isinstance(param, float):
  3715. param_name = [k for k, v in locals().items() if v is param][0]
  3716. self.app.inform.emit(_("[WARNING] Invalid value for {}").format(param))
  3717. results = []
  3718. if overlap >= 1:
  3719. self.app.inform.emit(
  3720. _("[ERROR_NOTCL] Could not do Paint. Overlap value has to be less than 1.00 (100%)."))
  3721. return
  3722. def recurse(geometry, reset=True):
  3723. """
  3724. Creates a list of non-iterable linear geometry objects.
  3725. Results are placed in self.flat_geometry
  3726. :param geometry: Shapely type or list or list of list of such.
  3727. :param reset: Clears the contents of self.flat_geometry.
  3728. """
  3729. if geometry is None:
  3730. return
  3731. if reset:
  3732. self.flat_geo = []
  3733. ## If iterable, expand recursively.
  3734. try:
  3735. for geo in geometry:
  3736. if geo is not None:
  3737. recurse(geometry=geo, reset=False)
  3738. ## Not iterable, do the actual indexing and add.
  3739. except TypeError:
  3740. self.flat_geo.append(geometry)
  3741. return self.flat_geo
  3742. for geo in selected:
  3743. local_results = []
  3744. for geo_obj in recurse(geo.geo):
  3745. try:
  3746. if type(geo_obj) == Polygon:
  3747. poly_buf = geo_obj.buffer(-margin)
  3748. else:
  3749. poly_buf = Polygon(geo_obj).buffer(-margin)
  3750. if method == "seed":
  3751. cp = Geometry.clear_polygon2(poly_buf,
  3752. tooldia, self.app.defaults["geometry_circle_steps"],
  3753. overlap=overlap, contour=contour, connect=connect)
  3754. elif method == "lines":
  3755. cp = Geometry.clear_polygon3(poly_buf,
  3756. tooldia, self.app.defaults["geometry_circle_steps"],
  3757. overlap=overlap, contour=contour, connect=connect)
  3758. else:
  3759. cp = Geometry.clear_polygon(poly_buf,
  3760. tooldia, self.app.defaults["geometry_circle_steps"],
  3761. overlap=overlap, contour=contour, connect=connect)
  3762. if cp is not None:
  3763. local_results += list(cp.get_objects())
  3764. except Exception as e:
  3765. log.debug("Could not Paint the polygons. %s" % str(e))
  3766. self.app.inform.emit(
  3767. _("[ERROR] Could not do Paint. Try a different combination of parameters. "
  3768. "Or a different method of Paint\n%s") % str(e))
  3769. return
  3770. # add the result to the results list
  3771. results.append(cascaded_union(local_results))
  3772. # This is a dirty patch:
  3773. for r in results:
  3774. self.add_shape(DrawToolShape(r))
  3775. self.app.inform.emit(
  3776. _("[success] Paint done."))
  3777. self.replot()
  3778. class FlatCAMExcEditor(QtCore.QObject):
  3779. draw_shape_idx = -1
  3780. def __init__(self, app):
  3781. assert isinstance(app, FlatCAMApp.App), \
  3782. "Expected the app to be a FlatCAMApp.App, got %s" % type(app)
  3783. super(FlatCAMExcEditor, self).__init__()
  3784. self.app = app
  3785. self.canvas = self.app.plotcanvas
  3786. self.exc_edit_widget = QtWidgets.QWidget()
  3787. layout = QtWidgets.QVBoxLayout()
  3788. self.exc_edit_widget.setLayout(layout)
  3789. ## Page Title box (spacing between children)
  3790. self.title_box = QtWidgets.QHBoxLayout()
  3791. layout.addLayout(self.title_box)
  3792. ## Page Title icon
  3793. pixmap = QtGui.QPixmap('share/flatcam_icon32.png')
  3794. self.icon = QtWidgets.QLabel()
  3795. self.icon.setPixmap(pixmap)
  3796. self.title_box.addWidget(self.icon, stretch=0)
  3797. ## Title label
  3798. self.title_label = QtWidgets.QLabel("<font size=5><b>%s</b></font>" % _('Excellon Editor'))
  3799. self.title_label.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
  3800. self.title_box.addWidget(self.title_label, stretch=1)
  3801. ## Object name
  3802. self.name_box = QtWidgets.QHBoxLayout()
  3803. layout.addLayout(self.name_box)
  3804. name_label = QtWidgets.QLabel(_("Name:"))
  3805. self.name_box.addWidget(name_label)
  3806. self.name_entry = FCEntry()
  3807. self.name_box.addWidget(self.name_entry)
  3808. ## Box box for custom widgets
  3809. # This gets populated in offspring implementations.
  3810. self.custom_box = QtWidgets.QVBoxLayout()
  3811. layout.addLayout(self.custom_box)
  3812. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  3813. # this way I can hide/show the frame
  3814. self.drills_frame = QtWidgets.QFrame()
  3815. self.drills_frame.setContentsMargins(0, 0, 0, 0)
  3816. self.custom_box.addWidget(self.drills_frame)
  3817. self.tools_box = QtWidgets.QVBoxLayout()
  3818. self.tools_box.setContentsMargins(0, 0, 0, 0)
  3819. self.drills_frame.setLayout(self.tools_box)
  3820. #### Tools Drills ####
  3821. self.tools_table_label = QtWidgets.QLabel("<b>%s</b>" % _('Tools Table'))
  3822. self.tools_table_label.setToolTip(
  3823. _( "Tools in this Excellon object\n"
  3824. "when are used for drilling.")
  3825. )
  3826. self.tools_box.addWidget(self.tools_table_label)
  3827. self.tools_table_exc = FCTable()
  3828. self.tools_box.addWidget(self.tools_table_exc)
  3829. self.tools_table_exc.setColumnCount(4)
  3830. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  3831. self.tools_table_exc.setSortingEnabled(False)
  3832. self.tools_table_exc.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)
  3833. self.empty_label = QtWidgets.QLabel('')
  3834. self.tools_box.addWidget(self.empty_label)
  3835. #### Add a new Tool ####
  3836. self.addtool_label = QtWidgets.QLabel('<b>%s</b>' % _('Add/Delete Tool'))
  3837. self.addtool_label.setToolTip(
  3838. _("Add/Delete a tool to the tool list\n"
  3839. "for this Excellon object.")
  3840. )
  3841. self.tools_box.addWidget(self.addtool_label)
  3842. grid1 = QtWidgets.QGridLayout()
  3843. self.tools_box.addLayout(grid1)
  3844. addtool_entry_lbl = QtWidgets.QLabel(_('Tool Dia:'))
  3845. addtool_entry_lbl.setToolTip(
  3846. _("Diameter for the new tool")
  3847. )
  3848. grid1.addWidget(addtool_entry_lbl, 0, 0)
  3849. hlay = QtWidgets.QHBoxLayout()
  3850. self.addtool_entry = FCEntry()
  3851. self.addtool_entry.setValidator(QtGui.QDoubleValidator(0.0001, 99.9999, 4))
  3852. hlay.addWidget(self.addtool_entry)
  3853. self.addtool_btn = QtWidgets.QPushButton(_('Add Tool'))
  3854. self.addtool_btn.setToolTip(
  3855. _( "Add a new tool to the tool list\n"
  3856. "with the diameter specified above.")
  3857. )
  3858. self.addtool_btn.setFixedWidth(80)
  3859. hlay.addWidget(self.addtool_btn)
  3860. grid1.addLayout(hlay, 0, 1)
  3861. grid2 = QtWidgets.QGridLayout()
  3862. self.tools_box.addLayout(grid2)
  3863. self.deltool_btn = QtWidgets.QPushButton(_('Delete Tool'))
  3864. self.deltool_btn.setToolTip(
  3865. _( "Delete a tool in the tool list\n"
  3866. "by selecting a row in the tool table.")
  3867. )
  3868. grid2.addWidget(self.deltool_btn, 0, 1)
  3869. # add a frame and inside add a vertical box layout. Inside this vbox layout I add all the Drills widgets
  3870. # this way I can hide/show the frame
  3871. self.resize_frame = QtWidgets.QFrame()
  3872. self.resize_frame.setContentsMargins(0, 0, 0, 0)
  3873. self.tools_box.addWidget(self.resize_frame)
  3874. self.resize_box = QtWidgets.QVBoxLayout()
  3875. self.resize_box.setContentsMargins(0, 0, 0, 0)
  3876. self.resize_frame.setLayout(self.resize_box)
  3877. #### Resize a drill ####
  3878. self.emptyresize_label = QtWidgets.QLabel('')
  3879. self.resize_box.addWidget(self.emptyresize_label)
  3880. self.drillresize_label = QtWidgets.QLabel('<b>%s</b>' % _("Resize Drill(s)"))
  3881. self.drillresize_label.setToolTip(
  3882. _("Resize a drill or a selection of drills.")
  3883. )
  3884. self.resize_box.addWidget(self.drillresize_label)
  3885. grid3 = QtWidgets.QGridLayout()
  3886. self.resize_box.addLayout(grid3)
  3887. res_entry_lbl = QtWidgets.QLabel(_('Resize Dia:'))
  3888. res_entry_lbl.setToolTip(
  3889. _( "Diameter to resize to.")
  3890. )
  3891. grid3.addWidget(addtool_entry_lbl, 0, 0)
  3892. hlay2 = QtWidgets.QHBoxLayout()
  3893. self.resdrill_entry = LengthEntry()
  3894. hlay2.addWidget(self.resdrill_entry)
  3895. self.resize_btn = QtWidgets.QPushButton(_('Resize'))
  3896. self.resize_btn.setToolTip(
  3897. _("Resize drill(s)")
  3898. )
  3899. self.resize_btn.setFixedWidth(80)
  3900. hlay2.addWidget(self.resize_btn)
  3901. grid3.addLayout(hlay2, 0, 1)
  3902. self.resize_frame.hide()
  3903. # add a frame and inside add a vertical box layout. Inside this vbox layout I add
  3904. # all the add drill array widgets
  3905. # this way I can hide/show the frame
  3906. self.array_frame = QtWidgets.QFrame()
  3907. self.array_frame.setContentsMargins(0, 0, 0, 0)
  3908. self.tools_box.addWidget(self.array_frame)
  3909. self.array_box = QtWidgets.QVBoxLayout()
  3910. self.array_box.setContentsMargins(0, 0, 0, 0)
  3911. self.array_frame.setLayout(self.array_box)
  3912. #### Add DRILL Array ####
  3913. self.emptyarray_label = QtWidgets.QLabel('')
  3914. self.array_box.addWidget(self.emptyarray_label)
  3915. self.drillarray_label = QtWidgets.QLabel('<b>%s</b>' % _("Add Drill Array"))
  3916. self.drillarray_label.setToolTip(
  3917. _("Add an array of drills (linear or circular array)")
  3918. )
  3919. self.array_box.addWidget(self.drillarray_label)
  3920. self.array_type_combo = FCComboBox()
  3921. self.array_type_combo.setToolTip(
  3922. _( "Select the type of drills array to create.\n"
  3923. "It can be Linear X(Y) or Circular")
  3924. )
  3925. self.array_type_combo.addItem(_("Linear"))
  3926. self.array_type_combo.addItem(_("Circular"))
  3927. self.array_box.addWidget(self.array_type_combo)
  3928. self.array_form = QtWidgets.QFormLayout()
  3929. self.array_box.addLayout(self.array_form)
  3930. self.drill_array_size_label = QtWidgets.QLabel(_('Nr of drills:'))
  3931. self.drill_array_size_label.setToolTip(
  3932. _("Specify how many drills to be in the array.")
  3933. )
  3934. self.drill_array_size_label.setFixedWidth(100)
  3935. self.drill_array_size_entry = LengthEntry()
  3936. self.array_form.addRow(self.drill_array_size_label, self.drill_array_size_entry)
  3937. self.array_linear_frame = QtWidgets.QFrame()
  3938. self.array_linear_frame.setContentsMargins(0, 0, 0, 0)
  3939. self.array_box.addWidget(self.array_linear_frame)
  3940. self.linear_box = QtWidgets.QVBoxLayout()
  3941. self.linear_box.setContentsMargins(0, 0, 0, 0)
  3942. self.array_linear_frame.setLayout(self.linear_box)
  3943. self.linear_form = QtWidgets.QFormLayout()
  3944. self.linear_box.addLayout(self.linear_form)
  3945. self.drill_axis_label = QtWidgets.QLabel(_('Direction:'))
  3946. self.drill_axis_label.setToolTip(
  3947. _("Direction on which the linear array is oriented:\n"
  3948. "- 'X' - horizontal axis \n"
  3949. "- 'Y' - vertical axis or \n"
  3950. "- 'Angle' - a custom angle for the array inclination")
  3951. )
  3952. self.drill_axis_label.setFixedWidth(100)
  3953. self.drill_axis_radio = RadioSet([{'label': 'X', 'value': 'X'},
  3954. {'label': 'Y', 'value': 'Y'},
  3955. {'label': _('Angle'), 'value': 'A'}])
  3956. self.drill_axis_radio.set_value('X')
  3957. self.linear_form.addRow(self.drill_axis_label, self.drill_axis_radio)
  3958. self.drill_pitch_label = QtWidgets.QLabel(_('Pitch:'))
  3959. self.drill_pitch_label.setToolTip(
  3960. _("Pitch = Distance between elements of the array.")
  3961. )
  3962. self.drill_pitch_label.setFixedWidth(100)
  3963. self.drill_pitch_entry = LengthEntry()
  3964. self.linear_form.addRow(self.drill_pitch_label, self.drill_pitch_entry)
  3965. self.linear_angle_label = QtWidgets.QLabel(_('Angle:'))
  3966. self.linear_angle_label.setToolTip(
  3967. _( "Angle at which the linear array is placed.\n"
  3968. "The precision is of max 2 decimals.\n"
  3969. "Min value is: -359.99 degrees.\n"
  3970. "Max value is: 360.00 degrees.")
  3971. )
  3972. self.linear_angle_label.setFixedWidth(100)
  3973. self.linear_angle_spinner = FCDoubleSpinner()
  3974. self.linear_angle_spinner.set_precision(2)
  3975. self.linear_angle_spinner.setRange(-359.99, 360.00)
  3976. self.linear_form.addRow(self.linear_angle_label, self.linear_angle_spinner)
  3977. self.array_circular_frame = QtWidgets.QFrame()
  3978. self.array_circular_frame.setContentsMargins(0, 0, 0, 0)
  3979. self.array_box.addWidget(self.array_circular_frame)
  3980. self.circular_box = QtWidgets.QVBoxLayout()
  3981. self.circular_box.setContentsMargins(0, 0, 0, 0)
  3982. self.array_circular_frame.setLayout(self.circular_box)
  3983. self.drill_direction_label = QtWidgets.QLabel(_('Direction:'))
  3984. self.drill_direction_label.setToolTip(
  3985. _( "Direction for circular array."
  3986. "Can be CW = clockwise or CCW = counter clockwise.")
  3987. )
  3988. self.drill_direction_label.setFixedWidth(100)
  3989. self.circular_form = QtWidgets.QFormLayout()
  3990. self.circular_box.addLayout(self.circular_form)
  3991. self.drill_direction_radio = RadioSet([{'label': 'CW', 'value': 'CW'},
  3992. {'label': 'CCW.', 'value': 'CCW'}])
  3993. self.drill_direction_radio.set_value('CW')
  3994. self.circular_form.addRow(self.drill_direction_label, self.drill_direction_radio)
  3995. self.drill_angle_label = QtWidgets.QLabel(_('Angle:'))
  3996. self.drill_angle_label.setToolTip(
  3997. _("Angle at which each element in circular array is placed.")
  3998. )
  3999. self.drill_angle_label.setFixedWidth(100)
  4000. self.drill_angle_entry = LengthEntry()
  4001. self.circular_form.addRow(self.drill_angle_label, self.drill_angle_entry)
  4002. self.array_circular_frame.hide()
  4003. self.linear_angle_spinner.hide()
  4004. self.linear_angle_label.hide()
  4005. self.array_frame.hide()
  4006. self.tools_box.addStretch()
  4007. ## Toolbar events and properties
  4008. self.tools_exc = {
  4009. "select": {"button": self.app.ui.select_drill_btn,
  4010. "constructor": FCDrillSelect},
  4011. "drill_add": {"button": self.app.ui.add_drill_btn,
  4012. "constructor": FCDrillAdd},
  4013. "drill_array": {"button": self.app.ui.add_drill_array_btn,
  4014. "constructor": FCDrillArray},
  4015. "drill_resize": {"button": self.app.ui.resize_drill_btn,
  4016. "constructor": FCDrillResize},
  4017. "drill_copy": {"button": self.app.ui.copy_drill_btn,
  4018. "constructor": FCDrillCopy},
  4019. "drill_move": {"button": self.app.ui.move_drill_btn,
  4020. "constructor": FCDrillMove},
  4021. }
  4022. ### Data
  4023. self.active_tool = None
  4024. self.storage_dict = {}
  4025. self.current_storage = []
  4026. # build the data from the Excellon point into a dictionary
  4027. # {tool_dia: [geometry_in_points]}
  4028. self.points_edit = {}
  4029. self.sorted_diameters =[]
  4030. self.new_drills = []
  4031. self.new_tools = {}
  4032. self.new_slots = {}
  4033. self.new_tool_offset = {}
  4034. # dictionary to store the tool_row and diameters in Tool_table
  4035. # it will be updated everytime self.build_ui() is called
  4036. self.olddia_newdia = {}
  4037. self.tool2tooldia = {}
  4038. # this will store the value for the last selected tool, for use after clicking on canvas when the selection
  4039. # is cleared but as a side effect also the selected tool is cleared
  4040. self.last_tool_selected = None
  4041. self.utility = []
  4042. # this will flag if the Editor "tools" are launched from key shortcuts (True) or from menu toolbar (False)
  4043. self.launched_from_shortcuts = False
  4044. # this var will store the state of the toolbar before starting the editor
  4045. self.toolbar_old_state = False
  4046. self.app.ui.delete_drill_btn.triggered.connect(self.on_delete_btn)
  4047. self.name_entry.returnPressed.connect(self.on_name_activate)
  4048. self.addtool_btn.clicked.connect(self.on_tool_add)
  4049. # self.addtool_entry.editingFinished.connect(self.on_tool_add)
  4050. self.deltool_btn.clicked.connect(self.on_tool_delete)
  4051. self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  4052. self.array_type_combo.currentIndexChanged.connect(self.on_array_type_combo)
  4053. self.drill_axis_radio.activated_custom.connect(self.on_linear_angle_radio)
  4054. self.app.ui.exc_add_array_drill_menuitem.triggered.connect(self.exc_add_drill_array)
  4055. self.app.ui.exc_add_drill_menuitem.triggered.connect(self.exc_add_drill)
  4056. self.app.ui.exc_resize_drill_menuitem.triggered.connect(self.exc_resize_drills)
  4057. self.app.ui.exc_copy_drill_menuitem.triggered.connect(self.exc_copy_drills)
  4058. self.app.ui.exc_delete_drill_menuitem.triggered.connect(self.on_delete_btn)
  4059. self.app.ui.exc_move_drill_menuitem.triggered.connect(self.exc_move_drills)
  4060. # Init GUI
  4061. self.drill_array_size_entry.set_value(5)
  4062. self.drill_pitch_entry.set_value(2.54)
  4063. self.drill_angle_entry.set_value(12)
  4064. self.drill_direction_radio.set_value('CW')
  4065. self.drill_axis_radio.set_value('X')
  4066. self.exc_obj = None
  4067. # VisPy Visuals
  4068. self.shapes = self.app.plotcanvas.new_shape_collection(layers=1)
  4069. self.tool_shape = self.app.plotcanvas.new_shape_collection(layers=1)
  4070. self.app.pool_recreated.connect(self.pool_recreated)
  4071. # Remove from scene
  4072. self.shapes.enabled = False
  4073. self.tool_shape.enabled = False
  4074. ## List of selected shapes.
  4075. self.selected = []
  4076. self.move_timer = QtCore.QTimer()
  4077. self.move_timer.setSingleShot(True)
  4078. ## Current application units in Upper Case
  4079. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4080. self.key = None # Currently pressed key
  4081. self.modifiers = None
  4082. self.x = None # Current mouse cursor pos
  4083. self.y = None
  4084. # Current snapped mouse pos
  4085. self.snap_x = None
  4086. self.snap_y = None
  4087. self.pos = None
  4088. def make_callback(thetool):
  4089. def f():
  4090. self.on_tool_select(thetool)
  4091. return f
  4092. for tool in self.tools_exc:
  4093. self.tools_exc[tool]["button"].triggered.connect(make_callback(tool)) # Events
  4094. self.tools_exc[tool]["button"].setCheckable(True) # Checkable
  4095. self.options = {
  4096. "global_gridx": 0.1,
  4097. "global_gridy": 0.1,
  4098. "snap_max": 0.05,
  4099. "grid_snap": True,
  4100. "corner_snap": False,
  4101. "grid_gap_link": True
  4102. }
  4103. self.app.options_read_form()
  4104. for option in self.options:
  4105. if option in self.app.options:
  4106. self.options[option] = self.app.options[option]
  4107. self.rtree_exc_index = rtindex.Index()
  4108. # flag to show if the object was modified
  4109. self.is_modified = False
  4110. self.edited_obj_name = ""
  4111. # variable to store the total amount of drills per job
  4112. self.tot_drill_cnt = 0
  4113. self.tool_row = 0
  4114. # variable to store the total amount of slots per job
  4115. self.tot_slot_cnt = 0
  4116. self.tool_row_slots = 0
  4117. self.tool_row = 0
  4118. # store the status of the editor so the Delete at object level will not work until the edit is finished
  4119. self.editor_active = False
  4120. def entry2option(option, entry):
  4121. self.options[option] = float(entry.text())
  4122. # store the status of the editor so the Delete at object level will not work until the edit is finished
  4123. self.editor_active = False
  4124. def pool_recreated(self, pool):
  4125. self.shapes.pool = pool
  4126. self.tool_shape.pool = pool
  4127. @staticmethod
  4128. def make_storage():
  4129. ## Shape storage.
  4130. storage = FlatCAMRTreeStorage()
  4131. storage.get_points = DrawToolShape.get_pts
  4132. return storage
  4133. def set_ui(self):
  4134. # updated units
  4135. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4136. self.olddia_newdia.clear()
  4137. self.tool2tooldia.clear()
  4138. # build the self.points_edit dict {dimaters: [point_list]}
  4139. for drill in self.exc_obj.drills:
  4140. if drill['tool'] in self.exc_obj.tools:
  4141. if self.units == 'IN':
  4142. tool_dia = float('%.3f' % self.exc_obj.tools[drill['tool']]['C'])
  4143. else:
  4144. tool_dia = float('%.2f' % self.exc_obj.tools[drill['tool']]['C'])
  4145. try:
  4146. self.points_edit[tool_dia].append(drill['point'])
  4147. except KeyError:
  4148. self.points_edit[tool_dia] = [drill['point']]
  4149. # update the olddia_newdia dict to make sure we have an updated state of the tool_table
  4150. for key in self.points_edit:
  4151. self.olddia_newdia[key] = key
  4152. sort_temp = []
  4153. for diam in self.olddia_newdia:
  4154. sort_temp.append(float(diam))
  4155. self.sorted_diameters = sorted(sort_temp)
  4156. # populate self.intial_table_rows dict with the tool number as keys and tool diameters as values
  4157. for i in range(len(self.sorted_diameters)):
  4158. tt_dia = self.sorted_diameters[i]
  4159. self.tool2tooldia[i + 1] = tt_dia
  4160. def build_ui(self):
  4161. try:
  4162. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  4163. self.tools_table_exc.itemChanged.disconnect()
  4164. except:
  4165. pass
  4166. # updated units
  4167. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4168. # make a new name for the new Excellon object (the one with edited content)
  4169. self.edited_obj_name = self.exc_obj.options['name']
  4170. self.name_entry.set_value(self.edited_obj_name)
  4171. if self.units == "IN":
  4172. self.addtool_entry.set_value(0.039)
  4173. else:
  4174. self.addtool_entry.set_value(1.00)
  4175. sort_temp = []
  4176. for diam in self.olddia_newdia:
  4177. sort_temp.append(float(diam))
  4178. self.sorted_diameters = sorted(sort_temp)
  4179. # here, self.sorted_diameters will hold in a oblique way, the number of tools
  4180. n = len(self.sorted_diameters)
  4181. # we have (n+2) rows because there are 'n' tools, each a row, plus the last 2 rows for totals.
  4182. self.tools_table_exc.setRowCount(n + 2)
  4183. self.tot_drill_cnt = 0
  4184. self.tot_slot_cnt = 0
  4185. self.tool_row = 0
  4186. # this variable will serve as the real tool_number
  4187. tool_id = 0
  4188. for tool_no in self.sorted_diameters:
  4189. tool_id += 1
  4190. drill_cnt = 0 # variable to store the nr of drills per tool
  4191. slot_cnt = 0 # variable to store the nr of slots per tool
  4192. # Find no of drills for the current tool
  4193. for tool_dia in self.points_edit:
  4194. if float(tool_dia) == tool_no:
  4195. drill_cnt = len(self.points_edit[tool_dia])
  4196. self.tot_drill_cnt += drill_cnt
  4197. try:
  4198. # Find no of slots for the current tool
  4199. for slot in self.slots:
  4200. if slot['tool'] == tool_no:
  4201. slot_cnt += 1
  4202. self.tot_slot_cnt += slot_cnt
  4203. except AttributeError:
  4204. # log.debug("No slots in the Excellon file")
  4205. # slot editing not implemented
  4206. pass
  4207. id = QtWidgets.QTableWidgetItem('%d' % int(tool_id))
  4208. id.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4209. self.tools_table_exc.setItem(self.tool_row, 0, id) # Tool name/id
  4210. # Make sure that the drill diameter when in MM is with no more than 2 decimals
  4211. # There are no drill bits in MM with more than 3 decimals diameter
  4212. # For INCH the decimals should be no more than 3. There are no drills under 10mils
  4213. if self.units == 'MM':
  4214. dia = QtWidgets.QTableWidgetItem('%.2f' % self.olddia_newdia[tool_no])
  4215. else:
  4216. dia = QtWidgets.QTableWidgetItem('%.3f' % self.olddia_newdia[tool_no])
  4217. dia.setFlags(QtCore.Qt.ItemIsEnabled)
  4218. drill_count = QtWidgets.QTableWidgetItem('%d' % drill_cnt)
  4219. drill_count.setFlags(QtCore.Qt.ItemIsEnabled)
  4220. # if the slot number is zero is better to not clutter the GUI with zero's so we print a space
  4221. if slot_cnt > 0:
  4222. slot_count = QtWidgets.QTableWidgetItem('%d' % slot_cnt)
  4223. else:
  4224. slot_count = QtWidgets.QTableWidgetItem('')
  4225. slot_count.setFlags(QtCore.Qt.ItemIsEnabled)
  4226. self.tools_table_exc.setItem(self.tool_row, 1, dia) # Diameter
  4227. self.tools_table_exc.setItem(self.tool_row, 2, drill_count) # Number of drills per tool
  4228. self.tools_table_exc.setItem(self.tool_row, 3, slot_count) # Number of drills per tool
  4229. self.tool_row += 1
  4230. # make the diameter column editable
  4231. for row in range(self.tool_row):
  4232. self.tools_table_exc.item(row, 1).setFlags(
  4233. QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)
  4234. self.tools_table_exc.item(row, 2).setForeground(QtGui.QColor(0, 0, 0))
  4235. self.tools_table_exc.item(row, 3).setForeground(QtGui.QColor(0, 0, 0))
  4236. # add a last row with the Total number of drills
  4237. # HACK: made the text on this cell '9999' such it will always be the one before last when sorting
  4238. # it will have to have the foreground color (font color) white
  4239. empty = QtWidgets.QTableWidgetItem('9998')
  4240. empty.setForeground(QtGui.QColor(255, 255, 255))
  4241. empty.setFlags(empty.flags() ^ QtCore.Qt.ItemIsEnabled)
  4242. empty_b = QtWidgets.QTableWidgetItem('')
  4243. empty_b.setFlags(empty_b.flags() ^ QtCore.Qt.ItemIsEnabled)
  4244. label_tot_drill_count = QtWidgets.QTableWidgetItem(_('Total Drills'))
  4245. tot_drill_count = QtWidgets.QTableWidgetItem('%d' % self.tot_drill_cnt)
  4246. label_tot_drill_count.setFlags(label_tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4247. tot_drill_count.setFlags(tot_drill_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4248. self.tools_table_exc.setItem(self.tool_row, 0, empty)
  4249. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_drill_count)
  4250. self.tools_table_exc.setItem(self.tool_row, 2, tot_drill_count) # Total number of drills
  4251. self.tools_table_exc.setItem(self.tool_row, 3, empty_b)
  4252. font = QtGui.QFont()
  4253. font.setBold(True)
  4254. font.setWeight(75)
  4255. for k in [1, 2]:
  4256. self.tools_table_exc.item(self.tool_row, k).setForeground(QtGui.QColor(127, 0, 255))
  4257. self.tools_table_exc.item(self.tool_row, k).setFont(font)
  4258. self.tool_row += 1
  4259. # add a last row with the Total number of slots
  4260. # HACK: made the text on this cell '9999' such it will always be the last when sorting
  4261. # it will have to have the foreground color (font color) white
  4262. empty_2 = QtWidgets.QTableWidgetItem('9999')
  4263. empty_2.setForeground(QtGui.QColor(255, 255, 255))
  4264. empty_2.setFlags(empty_2.flags() ^ QtCore.Qt.ItemIsEnabled)
  4265. empty_3 = QtWidgets.QTableWidgetItem('')
  4266. empty_3.setFlags(empty_3.flags() ^ QtCore.Qt.ItemIsEnabled)
  4267. label_tot_slot_count = QtWidgets.QTableWidgetItem(_('Total Slots'))
  4268. tot_slot_count = QtWidgets.QTableWidgetItem('%d' % self.tot_slot_cnt)
  4269. label_tot_slot_count.setFlags(label_tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4270. tot_slot_count.setFlags(tot_slot_count.flags() ^ QtCore.Qt.ItemIsEnabled)
  4271. self.tools_table_exc.setItem(self.tool_row, 0, empty_2)
  4272. self.tools_table_exc.setItem(self.tool_row, 1, label_tot_slot_count)
  4273. self.tools_table_exc.setItem(self.tool_row, 2, empty_3)
  4274. self.tools_table_exc.setItem(self.tool_row, 3, tot_slot_count) # Total number of slots
  4275. for kl in [1, 2, 3]:
  4276. self.tools_table_exc.item(self.tool_row, kl).setFont(font)
  4277. self.tools_table_exc.item(self.tool_row, kl).setForeground(QtGui.QColor(0, 70, 255))
  4278. # all the tools are selected by default
  4279. self.tools_table_exc.selectColumn(0)
  4280. #
  4281. self.tools_table_exc.resizeColumnsToContents()
  4282. self.tools_table_exc.resizeRowsToContents()
  4283. vertical_header = self.tools_table_exc.verticalHeader()
  4284. # vertical_header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents)
  4285. vertical_header.hide()
  4286. self.tools_table_exc.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
  4287. horizontal_header = self.tools_table_exc.horizontalHeader()
  4288. horizontal_header.setSectionResizeMode(0, QtWidgets.QHeaderView.ResizeToContents)
  4289. horizontal_header.setSectionResizeMode(1, QtWidgets.QHeaderView.Stretch)
  4290. horizontal_header.setSectionResizeMode(2, QtWidgets.QHeaderView.ResizeToContents)
  4291. horizontal_header.setSectionResizeMode(3, QtWidgets.QHeaderView.ResizeToContents)
  4292. # horizontal_header.setStretchLastSection(True)
  4293. # self.tools_table_exc.setSortingEnabled(True)
  4294. # sort by tool diameter
  4295. self.tools_table_exc.sortItems(1)
  4296. # After sorting, to display also the number of drills in the right row we need to update self.initial_rows dict
  4297. # with the new order. Of course the last 2 rows in the tool table are just for display therefore we don't
  4298. # use them
  4299. self.tool2tooldia.clear()
  4300. for row in range(self.tools_table_exc.rowCount() - 2):
  4301. tool = int(self.tools_table_exc.item(row, 0).text())
  4302. diameter = float(self.tools_table_exc.item(row, 1).text())
  4303. self.tool2tooldia[tool] = diameter
  4304. self.tools_table_exc.setMinimumHeight(self.tools_table_exc.getHeight())
  4305. self.tools_table_exc.setMaximumHeight(self.tools_table_exc.getHeight())
  4306. # make sure no rows are selected so the user have to click the correct row, meaning selecting the correct tool
  4307. self.tools_table_exc.clearSelection()
  4308. # Remove anything else in the GUI Selected Tab
  4309. self.app.ui.selected_scroll_area.takeWidget()
  4310. # Put ourself in the GUI Selected Tab
  4311. self.app.ui.selected_scroll_area.setWidget(self.exc_edit_widget)
  4312. # Switch notebook to Selected page
  4313. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  4314. # we reactivate the signals after the after the tool adding as we don't need to see the tool been populated
  4315. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4316. def on_tool_add(self, tooldia=None):
  4317. self.is_modified = True
  4318. if tooldia:
  4319. tool_dia = tooldia
  4320. else:
  4321. try:
  4322. tool_dia = float(self.addtool_entry.get_value())
  4323. except ValueError:
  4324. # try to convert comma to decimal point. if it's still not working error message and return
  4325. try:
  4326. tool_dia = float(self.addtool_entry.get_value().replace(',', '.'))
  4327. except ValueError:
  4328. self.app.inform.emit(_("[ERROR_NOTCL]Wrong value format entered, "
  4329. "use a number.")
  4330. )
  4331. return
  4332. if tool_dia not in self.olddia_newdia:
  4333. storage_elem = FlatCAMGeoEditor.make_storage()
  4334. self.storage_dict[tool_dia] = storage_elem
  4335. # self.olddia_newdia dict keeps the evidence on current tools diameters as keys and gets updated on values
  4336. # each time a tool diameter is edited or added
  4337. self.olddia_newdia[tool_dia] = tool_dia
  4338. else:
  4339. self.app.inform.emit(_("[WARNING_NOTCL]Tool already in the original or actual tool list.\n"
  4340. "Save and reedit Excellon if you need to add this tool. ")
  4341. )
  4342. return
  4343. # since we add a new tool, we update also the initial state of the tool_table through it's dictionary
  4344. # we add a new entry in the tool2tooldia dict
  4345. self.tool2tooldia[len(self.olddia_newdia)] = tool_dia
  4346. self.app.inform.emit(_("[success]Added new tool with dia: %s %s") % (str(tool_dia), str(self.units)))
  4347. self.build_ui()
  4348. # make a quick sort through the tool2tooldia dict so we find which row to select
  4349. row_to_be_selected = None
  4350. for key in sorted(self.tool2tooldia):
  4351. if self.tool2tooldia[key] == tool_dia:
  4352. row_to_be_selected = int(key) - 1
  4353. break
  4354. self.tools_table_exc.selectRow(row_to_be_selected)
  4355. def on_tool_delete(self, dia=None):
  4356. self.is_modified = True
  4357. deleted_tool_dia_list = []
  4358. deleted_tool_offset_list = []
  4359. try:
  4360. if dia is None or dia is False:
  4361. # deleted_tool_dia = float(self.tools_table_exc.item(self.tools_table_exc.currentRow(), 1).text())
  4362. for index in self.tools_table_exc.selectionModel().selectedRows():
  4363. row = index.row()
  4364. deleted_tool_dia_list.append(float(self.tools_table_exc.item(row, 1).text()))
  4365. else:
  4366. if isinstance(dia, list):
  4367. for dd in dia:
  4368. deleted_tool_dia_list.append(float('%.4f' % dd))
  4369. else:
  4370. deleted_tool_dia_list.append(float('%.4f' % dia))
  4371. except:
  4372. self.app.inform.emit(_("[WARNING_NOTCL]Select a tool in Tool Table"))
  4373. return
  4374. for deleted_tool_dia in deleted_tool_dia_list:
  4375. # delete de tool offset
  4376. self.exc_obj.tool_offset.pop(float(deleted_tool_dia), None)
  4377. # delete the storage used for that tool
  4378. storage_elem = FlatCAMGeoEditor.make_storage()
  4379. self.storage_dict[deleted_tool_dia] = storage_elem
  4380. self.storage_dict.pop(deleted_tool_dia, None)
  4381. # I've added this flag_del variable because dictionary don't like
  4382. # having keys deleted while iterating through them
  4383. flag_del = []
  4384. # self.points_edit.pop(deleted_tool_dia, None)
  4385. for deleted_tool in self.tool2tooldia:
  4386. if self.tool2tooldia[deleted_tool] == deleted_tool_dia:
  4387. flag_del.append(deleted_tool)
  4388. if flag_del:
  4389. for tool_to_be_deleted in flag_del:
  4390. # delete the tool
  4391. self.tool2tooldia.pop(tool_to_be_deleted, None)
  4392. # delete also the drills from points_edit dict just in case we add the tool again, we don't want to show the
  4393. # number of drills from before was deleter
  4394. self.points_edit[deleted_tool_dia] = []
  4395. flag_del = []
  4396. self.olddia_newdia.pop(deleted_tool_dia, None)
  4397. self.app.inform.emit(_("[success]Deleted tool with dia: %s %s") % (str(deleted_tool_dia), str(self.units)))
  4398. self.replot()
  4399. # self.app.inform.emit("Could not delete selected tool")
  4400. self.build_ui()
  4401. def on_tool_edit(self):
  4402. # if connected, disconnect the signal from the slot on item_changed as it creates issues
  4403. self.tools_table_exc.itemChanged.disconnect()
  4404. # self.tools_table_exc.selectionModel().currentChanged.disconnect()
  4405. self.is_modified = True
  4406. geometry = []
  4407. current_table_dia_edited = None
  4408. if self.tools_table_exc.currentItem() is not None:
  4409. current_table_dia_edited = float(self.tools_table_exc.currentItem().text())
  4410. row_of_item_changed = self.tools_table_exc.currentRow()
  4411. # rows start with 0, tools start with 1 so we adjust the value by 1
  4412. key_in_tool2tooldia = row_of_item_changed + 1
  4413. dia_changed = self.tool2tooldia[key_in_tool2tooldia]
  4414. # tool diameter is not used so we create a new tool with the desired diameter
  4415. if current_table_dia_edited not in self.olddia_newdia.values():
  4416. # update the dict that holds as keys our initial diameters and as values the edited diameters
  4417. self.olddia_newdia[dia_changed] = current_table_dia_edited
  4418. # update the dict that holds tool_no as key and tool_dia as value
  4419. self.tool2tooldia[key_in_tool2tooldia] = current_table_dia_edited
  4420. # update the tool offset
  4421. modified_offset = self.exc_obj.tool_offset.pop(dia_changed)
  4422. self.exc_obj.tool_offset[current_table_dia_edited] = modified_offset
  4423. self.replot()
  4424. else:
  4425. # tool diameter is already in use so we move the drills from the prior tool to the new tool
  4426. factor = current_table_dia_edited / dia_changed
  4427. for shape in self.storage_dict[dia_changed].get_objects():
  4428. geometry.append(DrawToolShape(
  4429. MultiLineString([affinity.scale(subgeo, xfact=factor, yfact=factor) for subgeo in shape.geo])))
  4430. self.points_edit[current_table_dia_edited].append((0, 0))
  4431. self.add_exc_shape(geometry, self.storage_dict[current_table_dia_edited])
  4432. self.on_tool_delete(dia=dia_changed)
  4433. # delete the tool offset
  4434. self.exc_obj.tool_offset.pop(dia_changed, None)
  4435. # we reactivate the signals after the after the tool editing
  4436. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4437. # self.tools_table_exc.selectionModel().currentChanged.connect(self.on_row_selected)
  4438. def on_name_activate(self):
  4439. self.edited_obj_name = self.name_entry.get_value()
  4440. def activate(self):
  4441. self.connect_canvas_event_handlers()
  4442. # self.app.collection.view.keyPressed.connect(self.on_canvas_key)
  4443. self.shapes.enabled = True
  4444. self.tool_shape.enabled = True
  4445. # self.app.app_cursor.enabled = True
  4446. self.app.ui.snap_max_dist_entry.setEnabled(True)
  4447. self.app.ui.corner_snap_btn.setEnabled(True)
  4448. self.app.ui.snap_magnet.setVisible(True)
  4449. self.app.ui.corner_snap_btn.setVisible(True)
  4450. self.app.ui.exc_editor_menu.setDisabled(False)
  4451. self.app.ui.exc_editor_menu.menuAction().setVisible(True)
  4452. self.app.ui.update_obj_btn.setEnabled(True)
  4453. self.app.ui.e_editor_cmenu.setEnabled(True)
  4454. self.app.ui.exc_edit_toolbar.setDisabled(False)
  4455. self.app.ui.exc_edit_toolbar.setVisible(True)
  4456. # self.app.ui.snap_toolbar.setDisabled(False)
  4457. # start with GRID toolbar activated
  4458. if self.app.ui.grid_snap_btn.isChecked() is False:
  4459. self.app.ui.grid_snap_btn.trigger()
  4460. # Tell the App that the editor is active
  4461. self.editor_active = True
  4462. def deactivate(self):
  4463. self.disconnect_canvas_event_handlers()
  4464. self.clear()
  4465. self.app.ui.exc_edit_toolbar.setDisabled(True)
  4466. settings = QSettings("Open Source", "FlatCAM")
  4467. if settings.contains("layout"):
  4468. layout = settings.value('layout', type=str)
  4469. if layout == 'standard':
  4470. # self.app.ui.exc_edit_toolbar.setVisible(False)
  4471. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4472. self.app.ui.corner_snap_btn.setEnabled(False)
  4473. self.app.ui.snap_magnet.setVisible(False)
  4474. self.app.ui.corner_snap_btn.setVisible(False)
  4475. elif layout == 'compact':
  4476. # self.app.ui.exc_edit_toolbar.setVisible(True)
  4477. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4478. self.app.ui.corner_snap_btn.setEnabled(False)
  4479. self.app.ui.snap_magnet.setVisible(True)
  4480. self.app.ui.corner_snap_btn.setVisible(True)
  4481. else:
  4482. # self.app.ui.exc_edit_toolbar.setVisible(False)
  4483. self.app.ui.snap_max_dist_entry.setEnabled(False)
  4484. self.app.ui.corner_snap_btn.setEnabled(False)
  4485. self.app.ui.snap_magnet.setVisible(False)
  4486. self.app.ui.corner_snap_btn.setVisible(False)
  4487. # set the Editor Toolbar visibility to what was before entering in the Editor
  4488. self.app.ui.exc_edit_toolbar.setVisible(False) if self.toolbar_old_state is False \
  4489. else self.app.ui.exc_edit_toolbar.setVisible(True)
  4490. # Disable visuals
  4491. self.shapes.enabled = False
  4492. self.tool_shape.enabled = False
  4493. # self.app.app_cursor.enabled = False
  4494. # Tell the app that the editor is no longer active
  4495. self.editor_active = False
  4496. self.app.ui.exc_editor_menu.setDisabled(True)
  4497. self.app.ui.exc_editor_menu.menuAction().setVisible(False)
  4498. self.app.ui.update_obj_btn.setEnabled(False)
  4499. self.app.ui.g_editor_cmenu.setEnabled(False)
  4500. self.app.ui.e_editor_cmenu.setEnabled(False)
  4501. # Show original geometry
  4502. if self.exc_obj:
  4503. self.exc_obj.visible = True
  4504. def connect_canvas_event_handlers(self):
  4505. ## Canvas events
  4506. # make sure that the shortcuts key and mouse events will no longer be linked to the methods from FlatCAMApp
  4507. # but those from FlatCAMGeoEditor
  4508. self.app.plotcanvas.vis_disconnect('mouse_press', self.app.on_mouse_click_over_plot)
  4509. self.app.plotcanvas.vis_disconnect('mouse_move', self.app.on_mouse_move_over_plot)
  4510. self.app.plotcanvas.vis_disconnect('mouse_release', self.app.on_mouse_click_release_over_plot)
  4511. self.app.plotcanvas.vis_disconnect('mouse_double_click', self.app.on_double_click_over_plot)
  4512. self.app.collection.view.clicked.disconnect()
  4513. self.canvas.vis_connect('mouse_press', self.on_canvas_click)
  4514. self.canvas.vis_connect('mouse_move', self.on_canvas_move)
  4515. self.canvas.vis_connect('mouse_release', self.on_canvas_click_release)
  4516. def disconnect_canvas_event_handlers(self):
  4517. self.canvas.vis_disconnect('mouse_press', self.on_canvas_click)
  4518. self.canvas.vis_disconnect('mouse_move', self.on_canvas_move)
  4519. self.canvas.vis_disconnect('mouse_release', self.on_canvas_click_release)
  4520. # we restore the key and mouse control to FlatCAMApp method
  4521. self.app.plotcanvas.vis_connect('mouse_press', self.app.on_mouse_click_over_plot)
  4522. self.app.plotcanvas.vis_connect('mouse_move', self.app.on_mouse_move_over_plot)
  4523. self.app.plotcanvas.vis_connect('mouse_release', self.app.on_mouse_click_release_over_plot)
  4524. self.app.plotcanvas.vis_connect('mouse_double_click', self.app.on_double_click_over_plot)
  4525. self.app.collection.view.clicked.connect(self.app.collection.on_mouse_down)
  4526. def clear(self):
  4527. self.active_tool = None
  4528. # self.shape_buffer = []
  4529. self.selected = []
  4530. self.points_edit = {}
  4531. self.new_tools = {}
  4532. self.new_drills = []
  4533. self.storage_dict = {}
  4534. self.shapes.clear(update=True)
  4535. self.tool_shape.clear(update=True)
  4536. # self.storage = FlatCAMExcEditor.make_storage()
  4537. self.replot()
  4538. def edit_fcexcellon(self, exc_obj):
  4539. """
  4540. Imports the geometry from the given FlatCAM Excellon object
  4541. into the editor.
  4542. :param fcgeometry: FlatCAMExcellon
  4543. :return: None
  4544. """
  4545. assert isinstance(exc_obj, Excellon), \
  4546. "Expected an Excellon Object, got %s" % type(exc_obj)
  4547. self.deactivate()
  4548. self.activate()
  4549. # Hide original geometry
  4550. self.exc_obj = exc_obj
  4551. exc_obj.visible = False
  4552. # Set selection tolerance
  4553. # DrawToolShape.tolerance = fc_excellon.drawing_tolerance * 10
  4554. self.select_tool("select")
  4555. self.set_ui()
  4556. # now that we hava data, create the GUI interface and add it to the Tool Tab
  4557. self.build_ui()
  4558. # we activate this after the initial build as we don't need to see the tool been populated
  4559. self.tools_table_exc.itemChanged.connect(self.on_tool_edit)
  4560. # build the geometry for each tool-diameter, each drill will be represented by a '+' symbol
  4561. # and then add it to the storage elements (each storage elements is a member of a list
  4562. for tool_dia in self.points_edit:
  4563. storage_elem = FlatCAMGeoEditor.make_storage()
  4564. for point in self.points_edit[tool_dia]:
  4565. # make a '+' sign, the line length is the tool diameter
  4566. start_hor_line = ((point.x - (tool_dia / 2)), point.y)
  4567. stop_hor_line = ((point.x + (tool_dia / 2)), point.y)
  4568. start_vert_line = (point.x, (point.y - (tool_dia / 2)))
  4569. stop_vert_line = (point.x, (point.y + (tool_dia / 2)))
  4570. shape = MultiLineString([(start_hor_line, stop_hor_line),(start_vert_line, stop_vert_line)])
  4571. if shape is not None:
  4572. self.add_exc_shape(DrawToolShape(shape), storage_elem)
  4573. self.storage_dict[tool_dia] = storage_elem
  4574. self.replot()
  4575. # add a first tool in the Tool Table but only if the Excellon Object is empty
  4576. if not self.tool2tooldia:
  4577. self.on_tool_add(tooldia=1.00)
  4578. def update_fcexcellon(self, exc_obj):
  4579. """
  4580. Create a new Excellon object that contain the edited content of the source Excellon object
  4581. :param exc_obj: FlatCAMExcellon
  4582. :return: None
  4583. """
  4584. # this dictionary will contain tooldia's as keys and a list of coordinates tuple as values
  4585. # the values of this dict are coordinates of the holes (drills)
  4586. edited_points = {}
  4587. for storage_tooldia in self.storage_dict:
  4588. for x in self.storage_dict[storage_tooldia].get_objects():
  4589. # all x.geo in self.storage_dict[storage] are MultiLinestring objects
  4590. # each MultiLineString is made out of Linestrings
  4591. # select first Linestring object in the current MultiLineString
  4592. first_linestring = x.geo[0]
  4593. # get it's coordinates
  4594. first_linestring_coords = first_linestring.coords
  4595. x_coord = first_linestring_coords[0][0] + (float(storage_tooldia) / 2)
  4596. y_coord = first_linestring_coords[0][1]
  4597. # create a tuple with the coordinates (x, y) and add it to the list that is the value of the
  4598. # edited_points dictionary
  4599. point = (x_coord, y_coord)
  4600. if not storage_tooldia in edited_points:
  4601. edited_points[storage_tooldia] = [point]
  4602. else:
  4603. edited_points[storage_tooldia].append(point)
  4604. # recreate the drills and tools to be added to the new Excellon edited object
  4605. # first, we look in the tool table if one of the tool diameters was changed then
  4606. # append that a tuple formed by (old_dia, edited_dia) to a list
  4607. changed_key = []
  4608. for initial_dia in self.olddia_newdia:
  4609. edited_dia = self.olddia_newdia[initial_dia]
  4610. if edited_dia != initial_dia:
  4611. for old_dia in edited_points:
  4612. if old_dia == initial_dia:
  4613. changed_key.append((old_dia, edited_dia))
  4614. # if the initial_dia is not in edited_points it means it is a new tool with no drill points
  4615. # (and we have to add it)
  4616. # because in case we have drill points it will have to be already added in edited_points
  4617. # if initial_dia not in edited_points.keys():
  4618. # edited_points[initial_dia] = []
  4619. for el in changed_key:
  4620. edited_points[el[1]] = edited_points.pop(el[0])
  4621. # Let's sort the edited_points dictionary by keys (diameters) and store the result in a zipped list
  4622. # ordered_edited_points is a ordered list of tuples;
  4623. # element[0] of the tuple is the diameter and
  4624. # element[1] of the tuple is a list of coordinates (a tuple themselves)
  4625. ordered_edited_points = sorted(zip(edited_points.keys(), edited_points.values()))
  4626. current_tool = 0
  4627. for tool_dia in ordered_edited_points:
  4628. current_tool += 1
  4629. # create the self.tools for the new Excellon object (the one with edited content)
  4630. name = str(current_tool)
  4631. spec = {"C": float(tool_dia[0])}
  4632. self.new_tools[name] = spec
  4633. # add in self.tools the 'solid_geometry' key, the value (a list) is populated bellow
  4634. self.new_tools[name]['solid_geometry'] = []
  4635. # create the self.drills for the new Excellon object (the one with edited content)
  4636. for point in tool_dia[1]:
  4637. self.new_drills.append(
  4638. {
  4639. 'point': Point(point),
  4640. 'tool': str(current_tool)
  4641. }
  4642. )
  4643. # repopulate the 'solid_geometry' for each tool
  4644. poly = Point(point).buffer(float(tool_dia[0]) / 2.0, int(int(exc_obj.geo_steps_per_circle) / 4))
  4645. self.new_tools[name]['solid_geometry'].append(poly)
  4646. if self.is_modified is True:
  4647. if "_edit" in self.edited_obj_name:
  4648. try:
  4649. id = int(self.edited_obj_name[-1]) + 1
  4650. self.edited_obj_name = self.edited_obj_name[:-1] + str(id)
  4651. except ValueError:
  4652. self.edited_obj_name += "_1"
  4653. else:
  4654. self.edited_obj_name += "_edit"
  4655. self.app.worker_task.emit({'fcn': self.new_edited_excellon,
  4656. 'params': [self.edited_obj_name]})
  4657. if self.exc_obj.slots:
  4658. self.new_slots = self.exc_obj.slots
  4659. self.new_tool_offset = self.exc_obj.tool_offset
  4660. # reset the tool table
  4661. self.tools_table_exc.clear()
  4662. self.tools_table_exc.setHorizontalHeaderLabels(['#', _('Diameter'), 'D', 'S'])
  4663. self.last_tool_selected = None
  4664. # delete the edited Excellon object which will be replaced by a new one having the edited content of the first
  4665. self.app.collection.set_active(self.exc_obj.options['name'])
  4666. self.app.collection.delete_active()
  4667. # restore GUI to the Selected TAB
  4668. # Remove anything else in the GUI
  4669. self.app.ui.tool_scroll_area.takeWidget()
  4670. # Switch notebook to Selected page
  4671. self.app.ui.notebook.setCurrentWidget(self.app.ui.selected_tab)
  4672. def update_options(self, obj):
  4673. try:
  4674. if not obj.options:
  4675. obj.options = {}
  4676. obj.options['xmin'] = 0
  4677. obj.options['ymin'] = 0
  4678. obj.options['xmax'] = 0
  4679. obj.options['ymax'] = 0
  4680. return True
  4681. else:
  4682. return False
  4683. except AttributeError:
  4684. obj.options = {}
  4685. return True
  4686. def new_edited_excellon(self, outname):
  4687. """
  4688. Creates a new Excellon object for the edited Excellon. Thread-safe.
  4689. :param outname: Name of the resulting object. None causes the
  4690. name to be that of the file.
  4691. :type outname: str
  4692. :return: None
  4693. """
  4694. self.app.log.debug("Update the Excellon object with edited content. Source is %s" %
  4695. self.exc_obj.options['name'])
  4696. # How the object should be initialized
  4697. def obj_init(excellon_obj, app_obj):
  4698. # self.progress.emit(20)
  4699. excellon_obj.drills = self.new_drills
  4700. excellon_obj.tools = self.new_tools
  4701. excellon_obj.slots = self.new_slots
  4702. excellon_obj.tool_offset = self.new_tool_offset
  4703. excellon_obj.options['name'] = outname
  4704. try:
  4705. excellon_obj.create_geometry()
  4706. except KeyError:
  4707. self.app.inform.emit(
  4708. _( "[ERROR_NOTCL] There are no Tools definitions in the file. Aborting Excellon creation.")
  4709. )
  4710. except:
  4711. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  4712. msg += traceback.format_exc()
  4713. app_obj.inform.emit(msg)
  4714. raise
  4715. # raise
  4716. with self.app.proc_container.new(_("Creating Excellon.")):
  4717. try:
  4718. self.app.new_object("excellon", outname, obj_init)
  4719. except Exception as e:
  4720. log.error("Error on object creation: %s" % str(e))
  4721. self.app.progress.emit(100)
  4722. return
  4723. self.app.inform.emit(_("[success]Excellon editing finished."))
  4724. # self.progress.emit(100)
  4725. def on_tool_select(self, tool):
  4726. """
  4727. Behavior of the toolbar. Tool initialization.
  4728. :rtype : None
  4729. """
  4730. current_tool = tool
  4731. self.app.log.debug("on_tool_select('%s')" % tool)
  4732. if self.last_tool_selected is None and current_tool is not 'select':
  4733. # self.draw_app.select_tool('select')
  4734. self.complete = True
  4735. current_tool = 'select'
  4736. self.app.inform.emit(_("[WARNING_NOTCL]Cancelled. There is no Tool/Drill selected"))
  4737. # This is to make the group behave as radio group
  4738. if current_tool in self.tools_exc:
  4739. if self.tools_exc[current_tool]["button"].isChecked():
  4740. self.app.log.debug("%s is checked." % current_tool)
  4741. for t in self.tools_exc:
  4742. if t != current_tool:
  4743. self.tools_exc[t]["button"].setChecked(False)
  4744. # this is where the Editor toolbar classes (button's) are instantiated
  4745. self.active_tool = self.tools_exc[current_tool]["constructor"](self)
  4746. # self.app.inform.emit(self.active_tool.start_msg)
  4747. else:
  4748. self.app.log.debug("%s is NOT checked." % current_tool)
  4749. for t in self.tools_exc:
  4750. self.tools_exc[t]["button"].setChecked(False)
  4751. self.active_tool = None
  4752. def on_row_selected(self):
  4753. self.selected = []
  4754. try:
  4755. selected_dia = self.tool2tooldia[self.tools_table_exc.currentRow() + 1]
  4756. self.last_tool_selected = self.tools_table_exc.currentRow() + 1
  4757. for obj in self.storage_dict[selected_dia].get_objects():
  4758. self.selected.append(obj)
  4759. except Exception as e:
  4760. self.app.log.debug(str(e))
  4761. self.replot()
  4762. def toolbar_tool_toggle(self, key):
  4763. self.options[key] = self.sender().isChecked()
  4764. if self.options[key] == True:
  4765. return 1
  4766. else:
  4767. return 0
  4768. def on_canvas_click(self, event):
  4769. """
  4770. event.x and .y have canvas coordinates
  4771. event.xdaya and .ydata have plot coordinates
  4772. :param event: Event object dispatched by Matplotlib
  4773. :return: None
  4774. """
  4775. if event.button is 1:
  4776. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4777. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (0, 0))
  4778. self.pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  4779. ### Snap coordinates
  4780. x, y = self.app.geo_editor.snap(self.pos[0], self.pos[1])
  4781. self.pos = (x, y)
  4782. # print(self.active_tool)
  4783. # Selection with left mouse button
  4784. if self.active_tool is not None and event.button is 1:
  4785. # Dispatch event to active_tool
  4786. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  4787. msg = self.active_tool.click(self.app.geo_editor.snap(self.pos[0], self.pos[1]))
  4788. # If it is a shape generating tool
  4789. if isinstance(self.active_tool, FCShapeTool) and self.active_tool.complete:
  4790. if self.current_storage is not None:
  4791. self.on_exc_shape_complete(self.current_storage)
  4792. self.build_ui()
  4793. # MS: always return to the Select Tool if modifier key is not pressed
  4794. # else return to the current tool
  4795. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4796. if self.draw_app.app.defaults["global_mselect_key"] == 'Control':
  4797. modifier_to_use = Qt.ControlModifier
  4798. else:
  4799. modifier_to_use = Qt.ShiftModifier
  4800. # if modifier key is pressed then we add to the selected list the current shape but if it's already
  4801. # in the selected list, we removed it. Therefore first click selects, second deselects.
  4802. if key_modifier == modifier_to_use:
  4803. self.select_tool(self.active_tool.name)
  4804. else:
  4805. self.select_tool("select")
  4806. return
  4807. if isinstance(self.active_tool, FCDrillSelect):
  4808. # self.app.log.debug("Replotting after click.")
  4809. self.replot()
  4810. else:
  4811. self.app.log.debug("No active tool to respond to click!")
  4812. def on_exc_shape_complete(self, storage):
  4813. self.app.log.debug("on_shape_complete()")
  4814. # Add shape
  4815. if type(storage) is list:
  4816. for item_storage in storage:
  4817. self.add_exc_shape(self.active_tool.geometry, item_storage)
  4818. else:
  4819. self.add_exc_shape(self.active_tool.geometry, storage)
  4820. # Remove any utility shapes
  4821. self.delete_utility_geometry()
  4822. self.tool_shape.clear(update=True)
  4823. # Replot and reset tool.
  4824. self.replot()
  4825. # self.active_tool = type(self.active_tool)(self)
  4826. def add_exc_shape(self, shape, storage):
  4827. """
  4828. Adds a shape to the shape storage.
  4829. :param shape: Shape to be added.
  4830. :type shape: DrawToolShape
  4831. :return: None
  4832. """
  4833. # List of DrawToolShape?
  4834. if isinstance(shape, list):
  4835. for subshape in shape:
  4836. self.add_exc_shape(subshape, storage)
  4837. return
  4838. assert isinstance(shape, DrawToolShape), \
  4839. "Expected a DrawToolShape, got %s" % str(type(shape))
  4840. assert shape.geo is not None, \
  4841. "Shape object has empty geometry (None)"
  4842. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  4843. not isinstance(shape.geo, list), \
  4844. "Shape objects has empty geometry ([])"
  4845. if isinstance(shape, DrawToolUtilityShape):
  4846. self.utility.append(shape)
  4847. else:
  4848. storage.insert(shape) # TODO: Check performance
  4849. def add_shape(self, shape):
  4850. """
  4851. Adds a shape to the shape storage.
  4852. :param shape: Shape to be added.
  4853. :type shape: DrawToolShape
  4854. :return: None
  4855. """
  4856. # List of DrawToolShape?
  4857. if isinstance(shape, list):
  4858. for subshape in shape:
  4859. self.add_shape(subshape)
  4860. return
  4861. assert isinstance(shape, DrawToolShape), \
  4862. "Expected a DrawToolShape, got %s" % type(shape)
  4863. assert shape.geo is not None, \
  4864. "Shape object has empty geometry (None)"
  4865. assert (isinstance(shape.geo, list) and len(shape.geo) > 0) or \
  4866. not isinstance(shape.geo, list), \
  4867. "Shape objects has empty geometry ([])"
  4868. if isinstance(shape, DrawToolUtilityShape):
  4869. self.utility.append(shape)
  4870. else:
  4871. self.storage.insert(shape) # TODO: Check performance
  4872. def on_canvas_click_release(self, event):
  4873. pos_canvas = self.canvas.vispy_canvas.translate_coords(event.pos)
  4874. self.modifiers = QtWidgets.QApplication.keyboardModifiers()
  4875. if self.app.grid_status():
  4876. pos = self.app.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4877. else:
  4878. pos = (pos_canvas[0], pos_canvas[1])
  4879. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4880. # canvas menu
  4881. try:
  4882. if event.button == 2: # right click
  4883. if self.app.panning_action is True:
  4884. self.app.panning_action = False
  4885. else:
  4886. self.app.cursor = QtGui.QCursor()
  4887. self.app.ui.popMenu.popup(self.app.cursor.pos())
  4888. except Exception as e:
  4889. log.warning("Error: %s" % str(e))
  4890. raise
  4891. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4892. # selection and then select a type of selection ("enclosing" or "touching")
  4893. try:
  4894. if event.button == 1: # left click
  4895. if self.app.selection_type is not None:
  4896. self.draw_selection_area_handler(self.pos, pos, self.app.selection_type)
  4897. self.app.selection_type = None
  4898. elif isinstance(self.active_tool, FCDrillSelect):
  4899. # Dispatch event to active_tool
  4900. # msg = self.active_tool.click(self.app.geo_editor.snap(event.xdata, event.ydata))
  4901. # msg = self.active_tool.click_release((self.pos[0], self.pos[1]))
  4902. # self.app.inform.emit(msg)
  4903. self.active_tool.click_release((self.pos[0], self.pos[1]))
  4904. self.replot()
  4905. except Exception as e:
  4906. log.warning("Error: %s" % str(e))
  4907. raise
  4908. def draw_selection_area_handler(self, start_pos, end_pos, sel_type):
  4909. """
  4910. :param start_pos: mouse position when the selection LMB click was done
  4911. :param end_pos: mouse position when the left mouse button is released
  4912. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4913. :type Bool
  4914. :return:
  4915. """
  4916. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4917. self.app.delete_selection_shape()
  4918. for storage in self.storage_dict:
  4919. for obj in self.storage_dict[storage].get_objects():
  4920. if (sel_type is True and poly_selection.contains(obj.geo)) or \
  4921. (sel_type is False and poly_selection.intersects(obj.geo)):
  4922. if self.key == self.app.defaults["global_mselect_key"]:
  4923. if obj in self.selected:
  4924. self.selected.remove(obj)
  4925. else:
  4926. # add the object to the selected shapes
  4927. self.selected.append(obj)
  4928. else:
  4929. self.selected.append(obj)
  4930. # select the diameter of the selected shape in the tool table
  4931. for storage in self.storage_dict:
  4932. for shape_s in self.selected:
  4933. if shape_s in self.storage_dict[storage].get_objects():
  4934. for key in self.tool2tooldia:
  4935. if self.tool2tooldia[key] == storage:
  4936. item = self.tools_table_exc.item((key - 1), 1)
  4937. self.tools_table_exc.setCurrentItem(item)
  4938. self.last_tool_selected = key
  4939. # item.setSelected(True)
  4940. # self.exc_editor_app.tools_table_exc.selectItem(key - 1)
  4941. self.replot()
  4942. def on_canvas_move(self, event):
  4943. """
  4944. Called on 'mouse_move' event
  4945. event.pos have canvas screen coordinates
  4946. :param event: Event object dispatched by VisPy SceneCavas
  4947. :return: None
  4948. """
  4949. pos = self.canvas.vispy_canvas.translate_coords(event.pos)
  4950. event.xdata, event.ydata = pos[0], pos[1]
  4951. self.x = event.xdata
  4952. self.y = event.ydata
  4953. # Prevent updates on pan
  4954. # if len(event.buttons) > 0:
  4955. # return
  4956. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4957. if event.button == 2:
  4958. self.app.panning_action = True
  4959. return
  4960. else:
  4961. self.app.panning_action = False
  4962. try:
  4963. x = float(event.xdata)
  4964. y = float(event.ydata)
  4965. except TypeError:
  4966. return
  4967. if self.active_tool is None:
  4968. return
  4969. ### Snap coordinates
  4970. x, y = self.app.geo_editor.app.geo_editor.snap(x, y)
  4971. self.snap_x = x
  4972. self.snap_y = y
  4973. # update the position label in the infobar since the APP mouse event handlers are disconnected
  4974. self.app.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4975. "<b>Y</b>: %.4f" % (x, y))
  4976. if self.pos is None:
  4977. self.pos = (0, 0)
  4978. dx = x - self.pos[0]
  4979. dy = y - self.pos[1]
  4980. # update the reference position label in the infobar since the APP mouse event handlers are disconnected
  4981. self.app.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4982. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4983. ### Utility geometry (animated)
  4984. geo = self.active_tool.utility_geometry(data=(x, y))
  4985. if isinstance(geo, DrawToolShape) and geo.geo is not None:
  4986. # Remove any previous utility shape
  4987. self.tool_shape.clear(update=True)
  4988. self.draw_utility_geometry(geo=geo)
  4989. ### Selection area on canvas section ###
  4990. dx = pos[0] - self.pos[0]
  4991. if event.is_dragging == 1 and event.button == 1:
  4992. self.app.delete_selection_shape()
  4993. if dx < 0:
  4994. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y),
  4995. color=self.app.defaults["global_alt_sel_line"],
  4996. face_color=self.app.defaults['global_alt_sel_fill'])
  4997. self.app.selection_type = False
  4998. else:
  4999. self.app.draw_moving_selection_shape((self.pos[0], self.pos[1]), (x,y))
  5000. self.app.selection_type = True
  5001. else:
  5002. self.app.selection_type = None
  5003. # Update cursor
  5004. self.app.app_cursor.set_data(np.asarray([(x, y)]), symbol='++', edge_color='black', size=20)
  5005. def on_canvas_key_release(self, event):
  5006. self.key = None
  5007. def draw_utility_geometry(self, geo):
  5008. # Add the new utility shape
  5009. try:
  5010. # this case is for the Font Parse
  5011. for el in list(geo.geo):
  5012. if type(el) == MultiPolygon:
  5013. for poly in el:
  5014. self.tool_shape.add(
  5015. shape=poly,
  5016. color=(self.app.defaults["global_draw_color"] + '80'),
  5017. update=False,
  5018. layer=0,
  5019. tolerance=None
  5020. )
  5021. elif type(el) == MultiLineString:
  5022. for linestring in el:
  5023. self.tool_shape.add(
  5024. shape=linestring,
  5025. color=(self.app.defaults["global_draw_color"] + '80'),
  5026. update=False,
  5027. layer=0,
  5028. tolerance=None
  5029. )
  5030. else:
  5031. self.tool_shape.add(
  5032. shape=el,
  5033. color=(self.app.defaults["global_draw_color"] + '80'),
  5034. update=False,
  5035. layer=0,
  5036. tolerance=None
  5037. )
  5038. except TypeError:
  5039. self.tool_shape.add(
  5040. shape=geo.geo, color=(self.app.defaults["global_draw_color"] + '80'),
  5041. update=False, layer=0, tolerance=None)
  5042. self.tool_shape.redraw()
  5043. def replot(self):
  5044. self.plot_all()
  5045. def plot_all(self):
  5046. """
  5047. Plots all shapes in the editor.
  5048. :return: None
  5049. :rtype: None
  5050. """
  5051. # self.app.log.debug("plot_all()")
  5052. self.shapes.clear(update=True)
  5053. for storage in self.storage_dict:
  5054. for shape_plus in self.storage_dict[storage].get_objects():
  5055. if shape_plus.geo is None:
  5056. continue
  5057. if shape_plus in self.selected:
  5058. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_sel_draw_color'],
  5059. linewidth=2)
  5060. continue
  5061. self.plot_shape(geometry=shape_plus.geo, color=self.app.defaults['global_draw_color'])
  5062. # for shape in self.storage.get_objects():
  5063. # if shape.geo is None: # TODO: This shouldn't have happened
  5064. # continue
  5065. #
  5066. # if shape in self.selected:
  5067. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_sel_draw_color'], linewidth=2)
  5068. # continue
  5069. #
  5070. # self.plot_shape(geometry=shape.geo, color=self.app.defaults['global_draw_color'])
  5071. for shape in self.utility:
  5072. self.plot_shape(geometry=shape.geo, linewidth=1)
  5073. continue
  5074. self.shapes.redraw()
  5075. def plot_shape(self, geometry=None, color='black', linewidth=1):
  5076. """
  5077. Plots a geometric object or list of objects without rendering. Plotted objects
  5078. are returned as a list. This allows for efficient/animated rendering.
  5079. :param geometry: Geometry to be plotted (Any Shapely.geom kind or list of such)
  5080. :param color: Shape color
  5081. :param linewidth: Width of lines in # of pixels.
  5082. :return: List of plotted elements.
  5083. """
  5084. plot_elements = []
  5085. if geometry is None:
  5086. geometry = self.active_tool.geometry
  5087. try:
  5088. for geo in geometry:
  5089. plot_elements += self.plot_shape(geometry=geo, color=color, linewidth=linewidth)
  5090. ## Non-iterable
  5091. except TypeError:
  5092. ## DrawToolShape
  5093. if isinstance(geometry, DrawToolShape):
  5094. plot_elements += self.plot_shape(geometry=geometry.geo, color=color, linewidth=linewidth)
  5095. ## Polygon: Descend into exterior and each interior.
  5096. if type(geometry) == Polygon:
  5097. plot_elements += self.plot_shape(geometry=geometry.exterior, color=color, linewidth=linewidth)
  5098. plot_elements += self.plot_shape(geometry=geometry.interiors, color=color, linewidth=linewidth)
  5099. if type(geometry) == LineString or type(geometry) == LinearRing:
  5100. plot_elements.append(self.shapes.add(shape=geometry, color=color, layer=0))
  5101. if type(geometry) == Point:
  5102. pass
  5103. return plot_elements
  5104. def on_shape_complete(self):
  5105. self.app.log.debug("on_shape_complete()")
  5106. # Add shape
  5107. self.add_shape(self.active_tool.geometry)
  5108. # Remove any utility shapes
  5109. self.delete_utility_geometry()
  5110. self.tool_shape.clear(update=True)
  5111. # Replot and reset tool.
  5112. self.replot()
  5113. # self.active_tool = type(self.active_tool)(self)
  5114. def get_selected(self):
  5115. """
  5116. Returns list of shapes that are selected in the editor.
  5117. :return: List of shapes.
  5118. """
  5119. # return [shape for shape in self.shape_buffer if shape["selected"]]
  5120. return self.selected
  5121. def delete_selected(self):
  5122. temp_ref = [s for s in self.selected]
  5123. for shape_sel in temp_ref:
  5124. self.delete_shape(shape_sel)
  5125. self.selected = []
  5126. self.build_ui()
  5127. self.app.inform.emit(_("[success]Done. Drill(s) deleted."))
  5128. def delete_shape(self, shape):
  5129. self.is_modified = True
  5130. if shape in self.utility:
  5131. self.utility.remove(shape)
  5132. return
  5133. for storage in self.storage_dict:
  5134. # try:
  5135. # self.storage_dict[storage].remove(shape)
  5136. # except:
  5137. # pass
  5138. if shape in self.storage_dict[storage].get_objects():
  5139. self.storage_dict[storage].remove(shape)
  5140. # a hack to make the tool_table display less drills per diameter
  5141. # self.points_edit it's only useful first time when we load the data into the storage
  5142. # but is still used as referecen when building tool_table in self.build_ui()
  5143. # the number of drills displayed in column 2 is just a len(self.points_edit) therefore
  5144. # deleting self.points_edit elements (doesn't matter who but just the number) solved the display issue.
  5145. del self.points_edit[storage][0]
  5146. if shape in self.selected:
  5147. self.selected.remove(shape) # TODO: Check performance
  5148. def delete_utility_geometry(self):
  5149. # for_deletion = [shape for shape in self.shape_buffer if shape.utility]
  5150. # for_deletion = [shape for shape in self.storage.get_objects() if shape.utility]
  5151. for_deletion = [shape for shape in self.utility]
  5152. for shape in for_deletion:
  5153. self.delete_shape(shape)
  5154. self.tool_shape.clear(update=True)
  5155. self.tool_shape.redraw()
  5156. def on_delete_btn(self):
  5157. self.delete_selected()
  5158. self.replot()
  5159. def select_tool(self, toolname):
  5160. """
  5161. Selects a drawing tool. Impacts the object and GUI.
  5162. :param toolname: Name of the tool.
  5163. :return: None
  5164. """
  5165. self.tools_exc[toolname]["button"].setChecked(True)
  5166. self.on_tool_select(toolname)
  5167. def set_selected(self, shape):
  5168. # Remove and add to the end.
  5169. if shape in self.selected:
  5170. self.selected.remove(shape)
  5171. self.selected.append(shape)
  5172. def set_unselected(self, shape):
  5173. if shape in self.selected:
  5174. self.selected.remove(shape)
  5175. def on_array_type_combo(self):
  5176. if self.array_type_combo.currentIndex() == 0:
  5177. self.array_circular_frame.hide()
  5178. self.array_linear_frame.show()
  5179. else:
  5180. self.delete_utility_geometry()
  5181. self.array_circular_frame.show()
  5182. self.array_linear_frame.hide()
  5183. self.app.inform.emit(_("Click on the circular array Center position"))
  5184. def on_linear_angle_radio(self):
  5185. val = self.drill_axis_radio.get_value()
  5186. if val == 'A':
  5187. self.linear_angle_spinner.show()
  5188. self.linear_angle_label.show()
  5189. else:
  5190. self.linear_angle_spinner.hide()
  5191. self.linear_angle_label.hide()
  5192. def exc_add_drill(self):
  5193. self.select_tool('add')
  5194. return
  5195. def exc_add_drill_array(self):
  5196. self.select_tool('add_array')
  5197. return
  5198. def exc_resize_drills(self):
  5199. self.select_tool('resize')
  5200. return
  5201. def exc_copy_drills(self):
  5202. self.select_tool('copy')
  5203. return
  5204. def exc_move_drills(self):
  5205. self.select_tool('move')
  5206. return
  5207. def distance(pt1, pt2):
  5208. return sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) ** 2)
  5209. def mag(vec):
  5210. return sqrt(vec[0] ** 2 + vec[1] ** 2)
  5211. def poly2rings(poly):
  5212. return [poly.exterior] + [interior for interior in poly.interiors]