App.py 477 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719
  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. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from shapely.geometry import Point, MultiPolygon
  21. from io import StringIO
  22. from reportlab.graphics import renderPDF
  23. from reportlab.pdfgen import canvas
  24. from reportlab.lib.units import inch, mm
  25. from reportlab.lib.pagesizes import landscape, portrait
  26. from svglib.svglib import svg2rlg
  27. import gc
  28. from xml.dom.minidom import parseString as parse_xml_string
  29. from multiprocessing.connection import Listener, Client
  30. from multiprocessing import Pool
  31. import socket
  32. # ####################################################################################################################
  33. # ################################### Imports part of FlatCAM #############################################
  34. # ####################################################################################################################
  35. # Diverse
  36. from Common import LoudDict, color_variant, ExclusionAreas
  37. from Bookmark import BookmarkManager
  38. from AppDatabase import ToolsDB2
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. # FlatCAM AppObjects
  42. from defaults import FlatCAMDefaults
  43. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  44. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  45. from AppObjects.ObjectCollection import *
  46. from AppObjects.FlatCAMObj import FlatCAMObj
  47. from AppObjects.FlatCAMCNCJob import CNCJobObject
  48. from AppObjects.FlatCAMDocument import DocumentObject
  49. from AppObjects.FlatCAMExcellon import ExcellonObject
  50. from AppObjects.FlatCAMGeometry import GeometryObject
  51. from AppObjects.FlatCAMGerber import GerberObject
  52. from AppObjects.FlatCAMScript import ScriptObject
  53. # FlatCAM Parsing files
  54. from AppParsers.ParseExcellon import Excellon
  55. from AppParsers.ParseGerber import Gerber
  56. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  57. # FlatCAM AppGUI
  58. from AppGUI.PlotCanvas import *
  59. from AppGUI.PlotCanvasLegacy import *
  60. from AppGUI.FlatCAMGUI import *
  61. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  62. # FlatCAM Pre-processors
  63. from AppPreProcessor import load_preprocessors
  64. # FlatCAM AppEditors
  65. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  66. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  67. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  68. from AppEditors.FlatCAMTextEditor import TextEditor
  69. from AppParsers.ParseHPGL2 import HPGL2
  70. # FlatCAM Workers
  71. from AppProcess import *
  72. from AppWorkerStack import WorkerStack
  73. # FlatCAM Tools
  74. from AppTools import *
  75. # FlatCAM Translation
  76. import gettext
  77. import AppTranslation as fcTranslate
  78. import builtins
  79. if sys.platform == 'win32':
  80. import winreg
  81. from win32comext.shell import shell, shellcon
  82. fcTranslate.apply_language('strings')
  83. if '_' not in builtins.__dict__:
  84. _ = gettext.gettext
  85. class App(QtCore.QObject):
  86. """
  87. The main application class. The constructor starts the AppGUI.
  88. """
  89. # ###############################################################################################################
  90. # ########################################## App ################################################################
  91. # ###############################################################################################################
  92. # ###############################################################################################################
  93. # ######################################### LOGGING #############################################################
  94. # ###############################################################################################################
  95. log = logging.getLogger('base')
  96. log.setLevel(logging.DEBUG)
  97. # log.setLevel(logging.WARNING)
  98. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  99. handler = logging.StreamHandler()
  100. handler.setFormatter(formatter)
  101. log.addHandler(handler)
  102. # ###############################################################################################################
  103. # #################################### Get Cmd Line Options #####################################################
  104. # ###############################################################################################################
  105. cmd_line_shellfile = ''
  106. cmd_line_shellvar = ''
  107. cmd_line_headless = None
  108. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  109. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  110. "FlatCam.py --headless=1"
  111. try:
  112. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  113. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  114. "shellvar=",
  115. "headless=",
  116. "multiprocessing-fork="])
  117. except getopt.GetoptError:
  118. print(cmd_line_help)
  119. sys.exit(2)
  120. for opt, arg in cmd_line_options:
  121. if opt == '-h':
  122. print(cmd_line_help)
  123. sys.exit()
  124. elif opt == '--shellfile':
  125. cmd_line_shellfile = arg
  126. elif opt == '--shellvar':
  127. cmd_line_shellvar = arg
  128. elif opt == '--headless':
  129. try:
  130. cmd_line_headless = eval(arg)
  131. except NameError:
  132. pass
  133. # ###############################################################################################################
  134. # ################################### Version and VERSION DATE ##################################################
  135. # ###############################################################################################################
  136. version = 8.993
  137. version_date = "2020/08/01"
  138. beta = True
  139. engine = '3D'
  140. # current date now
  141. date = str(datetime.today()).rpartition('.')[0]
  142. date = ''.join(c for c in date if c not in ':-')
  143. date = date.replace(' ', '_')
  144. # ###############################################################################################################
  145. # ############################################ URLS's ###########################################################
  146. # ###############################################################################################################
  147. # URL for update checks and statistics
  148. version_url = "http://flatcam.org/version"
  149. # App URL
  150. app_url = "http://flatcam.org"
  151. # Manual URL
  152. manual_url = "http://flatcam.org/manual/index.html"
  153. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  154. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  155. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  156. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  157. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  158. # this variable will hold the project status
  159. # if True it will mean that the project was modified and not saved
  160. should_we_save = False
  161. # flag is True if saving action has been triggered
  162. save_in_progress = False
  163. # ###############################################################################################################
  164. # ####################################### APP Signals ######################################################
  165. # ###############################################################################################################
  166. # Inform the user
  167. # Handled by:
  168. # * App.info() --> Print on the status bar
  169. inform = QtCore.pyqtSignal(str)
  170. app_quit = QtCore.pyqtSignal()
  171. # General purpose background task
  172. worker_task = QtCore.pyqtSignal(dict)
  173. # File opened
  174. # Handled by:
  175. # * register_folder()
  176. # * register_recent()
  177. # Note: Setting the parameters to unicode does not seem
  178. # to have an effect. Then are received as Qstring
  179. # anyway.
  180. # File type and filename
  181. file_opened = QtCore.pyqtSignal(str, str)
  182. # File type and filename
  183. file_saved = QtCore.pyqtSignal(str, str)
  184. # Percentage of progress
  185. progress = QtCore.pyqtSignal(int)
  186. plots_updated = QtCore.pyqtSignal()
  187. # Emitted by new_object() and passes the new object as argument, plot flag.
  188. # on_object_created() adds the object to the collection, plots on appropriate flag
  189. # and emits new_object_available.
  190. object_created = QtCore.pyqtSignal(object, bool, bool)
  191. # Emitted when a object has been changed (like scaled, mirrored)
  192. object_changed = QtCore.pyqtSignal(object)
  193. # Emitted after object has been plotted.
  194. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  195. object_plotted = QtCore.pyqtSignal(object)
  196. # Emitted when a new object has been added or deleted from/to the collection
  197. object_status_changed = QtCore.pyqtSignal(object, str, str)
  198. message = QtCore.pyqtSignal(str, str, str)
  199. # Emmited when shell command is finished(one command only)
  200. shell_command_finished = QtCore.pyqtSignal(object)
  201. # Emitted when multiprocess pool has been recreated
  202. pool_recreated = QtCore.pyqtSignal(object)
  203. # Emitted when an unhandled exception happens
  204. # in the worker task.
  205. thread_exception = QtCore.pyqtSignal(object)
  206. # used to signal that there are arguments for the app
  207. args_at_startup = QtCore.pyqtSignal(list)
  208. # a reusable signal to replot a list of objects
  209. # should be disconnected after use so it can be reused
  210. replot_signal = pyqtSignal(list)
  211. # signal emitted when jumping
  212. jump_signal = pyqtSignal(tuple)
  213. # signal emitted when jumping
  214. locate_signal = pyqtSignal(tuple, str)
  215. # close app signal
  216. close_app_signal = pyqtSignal()
  217. # will perform the cleanup operation after a Graceful Exit
  218. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  219. # graphic residues behind
  220. cleanup = pyqtSignal()
  221. def __init__(self, user_defaults=True):
  222. """
  223. Starts the application.
  224. :return: app
  225. :rtype: App
  226. """
  227. super().__init__()
  228. App.log.info("FlatCAM Starting...")
  229. self.main_thread = QtWidgets.QApplication.instance().thread()
  230. # ############################################################################################################
  231. # ################# Setup the listening thread for another instance launching with args ######################
  232. # ############################################################################################################
  233. if sys.platform == 'win32' or sys.platform == 'linux':
  234. # make sure the thread is stored by using a self. otherwise it's garbage collected
  235. self.th = QtCore.QThread()
  236. self.th.start(priority=QtCore.QThread.LowestPriority)
  237. self.new_launch = ArgsThread()
  238. self.new_launch.open_signal[list].connect(self.on_startup_args)
  239. self.new_launch.moveToThread(self.th)
  240. self.new_launch.start.emit()
  241. # ############################################################################################################
  242. # # ######################################## OS-specific #####################################################
  243. # ############################################################################################################
  244. portable = False
  245. # Folder for user settings.
  246. if sys.platform == 'win32':
  247. if platform.architecture()[0] == '32bit':
  248. App.log.debug("Win32!")
  249. else:
  250. App.log.debug("Win64!")
  251. # #######################################################################################################
  252. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  253. # #######################################################################################################
  254. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  255. try:
  256. with open(config_file, 'r'):
  257. pass
  258. except FileNotFoundError:
  259. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  260. try:
  261. with open(config_file, 'r') as f:
  262. try:
  263. for line in f:
  264. param = str(line).replace('\n', '').rpartition('=')
  265. if param[0] == 'portable':
  266. try:
  267. portable = eval(param[2])
  268. except NameError:
  269. portable = False
  270. if param[0] == 'headless':
  271. if param[2].lower() == 'true':
  272. self.cmd_line_headless = 1
  273. else:
  274. self.cmd_line_headless = None
  275. except Exception as e:
  276. log.debug('App.__init__() -->%s' % str(e))
  277. return
  278. except FileNotFoundError as e:
  279. log.debug(str(e))
  280. pass
  281. if portable is False:
  282. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  283. else:
  284. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  285. self.os = 'windows'
  286. else: # Linux/Unix/MacOS
  287. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  288. self.os = 'unix'
  289. # ############################################################################################################
  290. # ################################# Setup folders and files ##################################################
  291. # ############################################################################################################
  292. if not os.path.exists(self.data_path):
  293. os.makedirs(self.data_path)
  294. App.log.debug('Created data folder: ' + self.data_path)
  295. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  296. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  297. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  298. if not os.path.exists(self.preprocessorpaths):
  299. os.makedirs(self.preprocessorpaths)
  300. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  301. # create geo_tools_db.FlatDB file if there is none
  302. try:
  303. f = open(self.data_path + '/geo_tools_db.FlatDB')
  304. f.close()
  305. except IOError:
  306. App.log.debug('Creating empty geo_tool_db.FlatDB')
  307. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  308. json.dump({}, f)
  309. f.close()
  310. # create current_defaults.FlatConfig file if there is none
  311. try:
  312. f = open(self.data_path + '/current_defaults.FlatConfig')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty current_defaults.FlatConfig')
  316. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  317. json.dump({}, f)
  318. f.close()
  319. # Write factory_defaults.FlatConfig file to disk
  320. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  321. # create a recent files json file if there is none
  322. try:
  323. f = open(self.data_path + '/recent.json')
  324. f.close()
  325. except IOError:
  326. App.log.debug('Creating empty recent.json')
  327. f = open(self.data_path + '/recent.json', 'w')
  328. json.dump([], f)
  329. f.close()
  330. # create a recent projects json file if there is none
  331. try:
  332. fp = open(self.data_path + '/recent_projects.json')
  333. fp.close()
  334. except IOError:
  335. App.log.debug('Creating empty recent_projects.json')
  336. fp = open(self.data_path + '/recent_projects.json', 'w')
  337. json.dump([], fp)
  338. fp.close()
  339. # Application directory. CHDIR to it. Otherwise, trying to load
  340. # AppGUI icons will fail as their path is relative.
  341. # This will fail under cx_freeze ...
  342. self.app_home = os.path.dirname(os.path.realpath(__file__))
  343. App.log.debug("Application path is " + self.app_home)
  344. App.log.debug("Started in " + os.getcwd())
  345. # cx_freeze workaround
  346. if os.path.isfile(self.app_home):
  347. self.app_home = os.path.dirname(self.app_home)
  348. os.chdir(self.app_home)
  349. # ############################################################################################################
  350. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  351. # ############################################################################################################
  352. self.defaults = FlatCAMDefaults()
  353. self.defaults["root_folder_path"] = self.app_home
  354. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  355. if user_defaults:
  356. self.defaults.load(filename=current_defaults_path)
  357. if self.defaults['units'] == 'MM':
  358. self.decimals = int(self.defaults['decimals_metric'])
  359. else:
  360. self.decimals = int(self.defaults['decimals_inch'])
  361. if self.defaults["global_gray_icons"] is False:
  362. self.resource_location = 'assets/resources'
  363. else:
  364. self.resource_location = 'assets/resources/dark_resources'
  365. self.current_units = self.defaults['units']
  366. # ###########################################################################################################
  367. # #################################### SETUP OBJECT CLASSES #################################################
  368. # ###########################################################################################################
  369. self.setup_obj_classes()
  370. # ###########################################################################################################
  371. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  372. # ###########################################################################################################
  373. self.pool = Pool()
  374. # ###########################################################################################################
  375. # ###################################### Setting the Splash Screen ##########################################
  376. # ###########################################################################################################
  377. splash_settings = QSettings("Open Source", "FlatCAM")
  378. if splash_settings.contains("splash_screen"):
  379. show_splash = splash_settings.value("splash_screen")
  380. else:
  381. splash_settings.setValue('splash_screen', 1)
  382. # This will write the setting to the platform specific storage.
  383. del splash_settings
  384. show_splash = 1
  385. if show_splash and self.cmd_line_headless != 1:
  386. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  387. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  388. # self.splash.setMask(splash_pix.mask())
  389. # move splashscreen to the current monitor
  390. desktop = QtWidgets.QApplication.desktop()
  391. screen = desktop.screenNumber(QtGui.QCursor.pos())
  392. current_screen_center = desktop.availableGeometry(screen).center()
  393. self.splash.move(current_screen_center - self.splash.rect().center())
  394. self.splash.show()
  395. self.splash.showMessage(_("FlatCAM is initializing ..."),
  396. alignment=Qt.AlignBottom | Qt.AlignLeft,
  397. color=QtGui.QColor("gray"))
  398. else:
  399. show_splash = 0
  400. # ###########################################################################################################
  401. # ######################################### Initialize AppGUI ##################################################
  402. # ###########################################################################################################
  403. # FlatCAM colors used in plotting
  404. self.FC_light_green = '#BBF268BF'
  405. self.FC_dark_green = '#006E20BF'
  406. self.FC_light_blue = '#a5a5ffbf'
  407. self.FC_dark_blue = '#0000ffbf'
  408. self.ui = FlatCAMGUI(self)
  409. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  410. if theme_settings.contains("theme"):
  411. theme = theme_settings.value('theme', type=str)
  412. else:
  413. theme = 'white'
  414. if self.defaults["global_cursor_color_enabled"]:
  415. self.cursor_color_3D = self.defaults["global_cursor_color"]
  416. else:
  417. if theme == 'white':
  418. self.cursor_color_3D = 'black'
  419. else:
  420. self.cursor_color_3D = 'gray'
  421. # update the defaults dict with the setting in QSetting
  422. self.defaults['global_theme'] = theme
  423. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  424. self.ui.final_save.connect(self.final_save)
  425. # set FlatCAM units in the Status bar
  426. self.set_screen_units(self.defaults['units'])
  427. # ###########################################################################################################
  428. # ########################################### AUTOSAVE SETUP ################################################
  429. # ###########################################################################################################
  430. self.block_autosave = False
  431. self.autosave_timer = QtCore.QTimer(self)
  432. self.save_project_auto_update()
  433. self.autosave_timer.timeout.connect(self.save_project_auto)
  434. # ###########################################################################################################
  435. # #################################### LOAD PREPROCESSORS ###################################################
  436. # ###########################################################################################################
  437. # ----------------------------------------- WARNING --------------------------------------------------------
  438. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  439. # That's because the number of preprocessors can vary and here the comboboxes are populated
  440. # -----------------------------------------------------------------------------------------------------------
  441. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  442. # the preprocessor file
  443. self.preprocessors = load_preprocessors(self)
  444. # make sure that always the 'default' preprocessor is the first item in the dictionary
  445. if 'default' in self.preprocessors.keys():
  446. new_ppp_dict = {}
  447. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  448. default_pp = self.preprocessors.pop('default')
  449. new_ppp_dict['default'] = default_pp
  450. # then add the rest of the keys
  451. for name, val_class in self.preprocessors.items():
  452. new_ppp_dict[name] = val_class
  453. # and now put back the ordered dict with 'default' key first
  454. self.preprocessors = new_ppp_dict
  455. for name in list(self.preprocessors.keys()):
  456. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  457. if name.partition('_')[0] == 'Paste':
  458. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  459. continue
  460. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  461. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  462. if name == 'hpgl':
  463. continue
  464. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  465. # ###########################################################################################################
  466. # ##################################### UPDATE PREFERENCES AppGUI FORMS ########################################
  467. # ###########################################################################################################
  468. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  469. inform=self.inform)
  470. self.preferencesUiManager.defaults_write_form()
  471. # When the self.defaults dictionary changes will update the Preferences AppGUI forms
  472. self.defaults.set_change_callback(self.on_defaults_dict_change)
  473. # ###########################################################################################################
  474. # ##################################### FIRST RUN SECTION ###################################################
  475. # ################################ It's done only once after install #####################################
  476. # ###########################################################################################################
  477. if self.defaults["first_run"] is True:
  478. # ONLY AT FIRST STARTUP INIT THE AppGUI LAYOUT TO 'COMPACT'
  479. initial_lay = 'minimal'
  480. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  481. # Set the combobox in Preferences to the current layout
  482. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  483. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  484. # after the first run, this object should be False
  485. self.defaults["first_run"] = False
  486. self.preferencesUiManager.save_defaults(silent=True)
  487. # ###########################################################################################################
  488. # ############################################ Data #########################################################
  489. # ###########################################################################################################
  490. self.recent = []
  491. self.recent_projects = []
  492. self.clipboard = QtWidgets.QApplication.clipboard()
  493. self.project_filename = None
  494. self.toggle_units_ignore = False
  495. # ###########################################################################################################
  496. # ########################################## LOAD LANGUAGES ################################################
  497. # ###########################################################################################################
  498. self.languages = fcTranslate.load_languages()
  499. for name in sorted(self.languages.values()):
  500. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  501. # ###########################################################################################################
  502. # ####################################### APPLY APP LANGUAGE ################################################
  503. # ###########################################################################################################
  504. ret_val = fcTranslate.apply_language('strings')
  505. if ret_val == "no language":
  506. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  507. log.debug("Could not find the Language files. The App strings are missing.")
  508. else:
  509. # make the current language the current selection on the language combobox
  510. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  511. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  512. # ###########################################################################################################
  513. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  514. # ###########################################################################################################
  515. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  516. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  517. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  518. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  519. self.defaults.propagate_defaults()
  520. # ###########################################################################################################
  521. # ######################################## UPDATE THE OPTIONS ###############################################
  522. # ###########################################################################################################
  523. self.options = LoudDict()
  524. # -----------------------------------------------------------------------------------------------------------
  525. # Update the self.options from the self.defaults
  526. # The self.defaults holds the application defaults while the self.options holds the object defaults
  527. # -----------------------------------------------------------------------------------------------------------
  528. # Copy app defaults to project options
  529. for def_key, def_val in self.defaults.items():
  530. self.options[def_key] = deepcopy(def_val)
  531. self.preferencesUiManager.show_preferences_gui()
  532. # ### End of Data ####
  533. # ###########################################################################################################
  534. # #################################### SETUP OBJECT COLLECTION ##############################################
  535. # ###########################################################################################################
  536. self.collection = ObjectCollection(self)
  537. self.ui.project_tab_layout.addWidget(self.collection.view)
  538. # ### Adjust tabs width ## ##
  539. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  540. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  541. self.collection.view.setMinimumWidth(290)
  542. self.log.debug("Finished creating Object Collection.")
  543. # ###########################################################################################################
  544. # ######################################## SETUP Plot Area ##################################################
  545. # ###########################################################################################################
  546. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  547. if self.defaults["global_graphic_engine"] == '3D':
  548. self.is_legacy = False
  549. else:
  550. self.is_legacy = True
  551. # Event signals disconnect id holders
  552. self.mp = None
  553. self.mm = None
  554. self.mr = None
  555. self.mdc = None
  556. self.mp_zc = None
  557. self.kp = None
  558. # Matplotlib axis
  559. self.axes = None
  560. if show_splash:
  561. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  562. "Canvas initialization started."),
  563. alignment=Qt.AlignBottom | Qt.AlignLeft,
  564. color=QtGui.QColor("gray"))
  565. start_plot_time = time.time() # debug
  566. self.plotcanvas = None
  567. self.app_cursor = None
  568. self.hover_shapes = None
  569. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  570. # setup the PlotCanvas
  571. self.on_plotcanvas_setup()
  572. end_plot_time = time.time()
  573. self.used_time = end_plot_time - start_plot_time
  574. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  575. if show_splash:
  576. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  577. "Canvas initialization started.\n"
  578. "Canvas initialization finished in"), '%.2f' % self.used_time),
  579. alignment=Qt.AlignBottom | Qt.AlignLeft,
  580. color=QtGui.QColor("gray"))
  581. self.ui.splitter.setStretchFactor(1, 2)
  582. # ###########################################################################################################
  583. # ############################################### SYS TRAY ##################################################
  584. # ###########################################################################################################
  585. if self.defaults["global_systray_icon"]:
  586. self.parent_w = QtWidgets.QWidget()
  587. if self.cmd_line_headless == 1:
  588. self.trayIcon = FlatCAMSystemTray(app=self,
  589. icon=QtGui.QIcon(self.resource_location +
  590. '/flatcam_icon32_green.png'),
  591. headless=True,
  592. parent=self.parent_w)
  593. else:
  594. self.trayIcon = FlatCAMSystemTray(app=self,
  595. icon=QtGui.QIcon(self.resource_location +
  596. '/flatcam_icon32_green.png'),
  597. parent=self.parent_w)
  598. # ###########################################################################################################
  599. # ############################################### Worker SETUP ##############################################
  600. # ###########################################################################################################
  601. if self.defaults["global_worker_number"]:
  602. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  603. else:
  604. self.workers = WorkerStack(workers_number=2)
  605. self.worker_task.connect(self.workers.add_task)
  606. self.log.debug("Finished creating Workers crew.")
  607. # ###########################################################################################################
  608. # ############################################# Activity Monitor ###########################################
  609. # ###########################################################################################################
  610. self.activity_view = FlatCAMActivityView(app=self)
  611. self.ui.infobar.addWidget(self.activity_view)
  612. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  613. # ###########################################################################################################
  614. # ############################################# Signal handling #############################################
  615. # ###########################################################################################################
  616. # ########################################## Custom signals ################################################
  617. # signal for displaying messages in status bar
  618. self.inform.connect(self.info)
  619. # signal to be called when the app is quiting
  620. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  621. self.message.connect(lambda: message_dialog(parent=self.ui))
  622. # self.progress.connect(self.set_progress_bar)
  623. # signals that are emitted when object state changes
  624. self.object_created.connect(self.on_object_created)
  625. self.object_changed.connect(self.on_object_changed)
  626. self.object_plotted.connect(self.on_object_plotted)
  627. self.plots_updated.connect(self.on_plots_updated)
  628. # signals emitted when file state change
  629. self.file_opened.connect(self.register_recent)
  630. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  631. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  632. # ########################################## Standard signals ###############################################
  633. # ### Menu
  634. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  635. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  636. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  637. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  638. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  639. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  640. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  641. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  642. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  643. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  644. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  645. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  646. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  647. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  648. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  649. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  650. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  651. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  652. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  653. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  654. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  655. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  656. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  657. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  658. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  659. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  660. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  661. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  662. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  663. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  664. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  665. self.ui.menufile_exit.triggered.connect(self.final_save)
  666. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  667. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  668. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  669. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  670. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  671. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  672. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  673. self.ui.menueditdelete.triggered.connect(self.on_delete)
  674. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  675. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  676. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  677. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  678. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  679. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  680. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  681. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  682. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  683. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  684. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  685. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  686. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  687. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  688. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  689. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  690. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  691. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  692. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  693. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  694. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  695. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  696. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  697. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  698. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  699. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  700. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  701. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  702. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  703. self.ui.menuview_replot.triggered.connect(self.plot_all)
  704. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  705. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  706. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  707. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  708. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  709. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  710. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  711. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  712. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  713. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  714. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  715. self.ui.menuhelp_about.triggered.connect(self.on_about)
  716. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  717. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  718. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  719. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  720. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  721. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  722. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  723. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  724. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  725. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  726. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  727. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  728. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  729. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  730. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  731. # ToolBar signals
  732. self.connect_toolbar_signals()
  733. # Notebook and Plot Tab Area signals
  734. # make the right click on the notebook tab and plot tab area tab raise a menu
  735. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  736. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  737. self.on_tab_setup_context_menu()
  738. # activate initial state
  739. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  740. # Context Menu
  741. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  742. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  743. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  744. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  745. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  746. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  747. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  748. self.ui.clearplot.triggered.connect(self.clear_plots)
  749. self.ui.replot.triggered.connect(self.plot_all)
  750. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  751. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  752. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  753. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  754. self.ui.popmenu_move.triggered.connect(self.obj_move)
  755. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  756. # Project Context Menu -> Color Setting
  757. for act in self.ui.menuprojectcolor.actions():
  758. act.triggered.connect(self.on_set_color_action_triggered)
  759. # ###########################################################################################################
  760. # #################################### AppGUI PREFERENCES SIGNALS ##############################################
  761. # ###########################################################################################################
  762. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  763. lambda: self.on_toggle_units(no_pref=False))
  764. # ##################################### Workspace Setting Signals ###########################################
  765. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  766. self.on_workspace_modified)
  767. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  768. self.on_workspace_modified
  769. )
  770. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  771. # ###########################################################################################################
  772. # ######################################## AppGUI SETTINGS SIGNALS #############################################
  773. # ###########################################################################################################
  774. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  775. # ######################################## Tools related signals ############################################
  776. # Film Tool
  777. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  778. self.on_film_color_entry)
  779. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  780. self.on_film_color_button)
  781. # QRCode Tool
  782. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  783. self.on_qrcode_fill_color_entry)
  784. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  785. self.on_qrcode_fill_color_button)
  786. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  787. self.on_qrcode_back_color_entry)
  788. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  789. self.on_qrcode_back_color_button)
  790. # portability changed signal
  791. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  792. # Object list
  793. self.collection.view.activated.connect(self.on_row_activated)
  794. self.collection.item_selected.connect(self.on_row_selected)
  795. self.object_status_changed.connect(self.on_collection_updated)
  796. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  797. # Export Excellon parameters.
  798. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  799. self.on_update_exc_export
  800. )
  801. # call it once to make sure it is updated at startup
  802. self.on_update_exc_export(state=self.defaults["excellon_update"])
  803. # when there are arguments at application startup this get launched
  804. self.args_at_startup[list].connect(self.on_startup_args)
  805. # ###########################################################################################################
  806. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  807. # ###########################################################################################################
  808. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  809. lambda: self.restore_extensions(ext_type='excellon'))
  810. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  811. lambda: self.restore_extensions(ext_type='gcode'))
  812. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  813. lambda: self.restore_extensions(ext_type='gerber'))
  814. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  815. lambda: self.delete_all_extensions(ext_type='excellon'))
  816. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  817. lambda: self.delete_all_extensions(ext_type='gcode'))
  818. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  819. lambda: self.delete_all_extensions(ext_type='gerber'))
  820. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  821. lambda: self.add_extension(ext_type='excellon'))
  822. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  823. lambda: self.add_extension(ext_type='gcode'))
  824. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  825. lambda: self.add_extension(ext_type='gerber'))
  826. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  827. lambda: self.del_extension(ext_type='excellon'))
  828. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  829. lambda: self.del_extension(ext_type='gcode'))
  830. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  831. lambda: self.del_extension(ext_type='gerber'))
  832. # connect the 'Apply' buttons from the Preferences/File Associations
  833. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  834. lambda: self.on_register_files(obj_type='excellon'))
  835. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  836. lambda: self.on_register_files(obj_type='gcode'))
  837. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  838. lambda: self.on_register_files(obj_type='gerber'))
  839. # ###########################################################################################################
  840. # ########################################### KEYWORDS SIGNALS ##############################################
  841. # ###########################################################################################################
  842. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  843. lambda: self.restore_extensions(ext_type='keyword'))
  844. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  845. lambda: self.delete_all_extensions(ext_type='keyword'))
  846. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  847. lambda: self.add_extension(ext_type='keyword'))
  848. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  849. lambda: self.del_extension(ext_type='keyword'))
  850. # connect the abort_all_tasks related slots to the related signals
  851. self.proc_container.idle_flag.connect(self.app_is_idle)
  852. # signal emitted when a tab is closed in the Plot Area
  853. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  854. # signal to close the application
  855. self.close_app_signal.connect(self.kill_app)
  856. # ################################# FINISHED CONNECTING SIGNALS #############################################
  857. # ###########################################################################################################
  858. # ###########################################################################################################
  859. # ###########################################################################################################
  860. self.log.debug("Finished connecting Signals.")
  861. # ###########################################################################################################
  862. # ########################################## Other setups ###################################################
  863. # ###########################################################################################################
  864. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  865. # depending on from where those tools are called different actions can be done
  866. self.call_source = 'app'
  867. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  868. self.tool_tab_locked = False
  869. # decide if to show or hide the Notebook side of the screen at startup
  870. if self.defaults["global_project_at_startup"] is True:
  871. self.ui.splitter.setSizes([1, 1])
  872. else:
  873. self.ui.splitter.setSizes([0, 1])
  874. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  875. self.setup_component_editor()
  876. # ###########################################################################################################
  877. # ####################################### Auto-complete KEYWORDS ############################################
  878. # ###########################################################################################################
  879. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  880. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  881. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  882. 'export_exc',
  883. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  884. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  885. 'interiors', 'isolate', 'join_excellon',
  886. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  887. 'mirror', 'ncc',
  888. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  889. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  890. 'options', 'origin',
  891. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  892. 'save', 'save_project',
  893. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  894. 'skew', 'subtract_poly', 'subtract_rectangle',
  895. 'version', 'write_gcode'
  896. ]
  897. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  898. 'Paste_1',
  899. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  900. 'Toolchange_manual', 'True', 'Users',
  901. 'all', 'auto', 'axis',
  902. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  903. 'contour', 'default',
  904. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  905. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  906. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  907. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  908. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  909. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  910. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  911. 'spacing_columns',
  912. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  913. 'toolchange_xy', 'toolchangez', 'travelz',
  914. 'tooldia', 'use_threads', 'value',
  915. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  916. ]
  917. self.tcl_keywords = [
  918. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  919. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  920. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  921. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  922. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  923. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  924. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  925. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  926. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  927. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  928. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  929. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  930. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  931. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  932. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  933. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  934. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  935. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  936. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  937. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  938. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  939. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  940. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  941. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  942. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  943. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  944. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  945. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  946. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  947. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  948. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  949. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  950. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  951. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  952. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  953. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  954. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  955. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  956. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  957. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  958. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  959. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  960. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  961. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  962. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  963. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  964. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  965. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  966. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  967. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  968. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  969. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  970. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  971. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  972. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  973. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  974. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  975. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  976. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  977. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  978. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  979. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  980. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  981. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  982. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  983. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  984. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  985. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  986. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  987. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  988. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  989. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  990. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  991. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  992. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  993. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  994. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  995. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  996. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  997. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  998. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  999. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1000. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1001. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1002. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1003. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1004. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1005. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1006. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1007. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1008. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1009. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1010. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1011. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1012. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1013. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1014. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1015. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1016. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1017. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1018. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1019. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1020. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1021. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1022. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1023. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1024. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1025. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1026. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1027. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1028. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1029. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1030. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1031. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1032. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1033. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1034. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1035. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1036. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1037. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1038. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1039. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1040. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1041. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1042. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1043. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1044. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1045. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1046. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1047. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1048. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1049. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1050. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1051. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1052. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1053. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1054. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1055. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1056. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1057. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1058. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1059. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1060. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1061. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1062. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1063. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1064. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1065. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1066. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1067. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1068. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1069. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1070. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1071. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1072. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1073. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1074. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1075. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1076. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1077. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1078. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1079. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1080. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1081. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1082. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1083. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1084. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1085. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1086. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1087. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1088. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1089. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1090. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1091. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1092. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1093. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1094. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1095. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1096. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1097. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1098. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1099. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1100. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1101. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1102. ]
  1103. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1104. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1105. # ###########################################################################################################
  1106. # ############################################## Shell SETUP ################################################
  1107. # ###########################################################################################################
  1108. self.shell = FCShell(app=self, version=self.version)
  1109. self.ui.shell_dock.setWidget(self.shell)
  1110. self.log.debug("TCL Shell has been initialized.")
  1111. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1112. if self.defaults["global_shell_at_startup"]:
  1113. self.ui.shell_dock.show()
  1114. else:
  1115. self.ui.shell_dock.hide()
  1116. # ###########################################################################################################
  1117. # ########################################## Tools and Plugins ##############################################
  1118. # ###########################################################################################################
  1119. self.dblsidedtool = None
  1120. self.distance_tool = None
  1121. self.distance_min_tool = None
  1122. self.panelize_tool = None
  1123. self.film_tool = None
  1124. self.paste_tool = None
  1125. self.calculator_tool = None
  1126. self.rules_tool = None
  1127. self.sub_tool = None
  1128. self.move_tool = None
  1129. self.cutout_tool = None
  1130. self.ncclear_tool = None
  1131. self.optimal_tool = None
  1132. self.paint_tool = None
  1133. self.transform_tool = None
  1134. self.properties_tool = None
  1135. self.pdf_tool = None
  1136. self.image_tool = None
  1137. self.pcb_wizard_tool = None
  1138. self.cal_exc_tool = None
  1139. self.qrcode_tool = None
  1140. self.copper_thieving_tool = None
  1141. self.fiducial_tool = None
  1142. self.edrills_tool = None
  1143. self.align_objects_tool = None
  1144. self.punch_tool = None
  1145. self.invert_tool = None
  1146. self.corners_tool = None
  1147. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1148. try:
  1149. self.install_tools()
  1150. except AttributeError as e:
  1151. log.debug("App.__init__() install tools() --> %s" % str(e))
  1152. # ###########################################################################################################
  1153. # ############################################ SETUP RECENT ITEMS ###########################################
  1154. # ###########################################################################################################
  1155. self.setup_recent_items()
  1156. # ###########################################################################################################
  1157. # ######################################### BookMarks Manager ###############################################
  1158. # ###########################################################################################################
  1159. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1160. self.install_bookmarks()
  1161. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1162. # ###########################################################################################################
  1163. # ########################################### Tools Database ################################################
  1164. # ###########################################################################################################
  1165. self.tools_db_tab = None
  1166. # ### System Font Parsing ###
  1167. # self.f_parse = ParseFont(self)
  1168. # self.parse_system_fonts()
  1169. # ###########################################################################################################
  1170. # ######################################### Check for updates ###############################################
  1171. # ###########################################################################################################
  1172. # Separate thread (Not worker)
  1173. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1174. if (self.beta is False or self.beta is None) and \
  1175. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1176. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1177. # self.thr2 = QtCore.QThread()
  1178. self.worker_task.emit({'fcn': self.version_check,
  1179. 'params': []})
  1180. # self.thr2.start(QtCore.QThread.LowPriority)
  1181. # ###########################################################################################################
  1182. # ##################################### Register files with FlatCAM; #######################################
  1183. # ################################### It works only for Windows for now ####################################
  1184. # ###########################################################################################################
  1185. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1186. self.on_register_files()
  1187. # ###########################################################################################################
  1188. # ######################################## Variables for global usage #######################################
  1189. # ###########################################################################################################
  1190. # hold the App units
  1191. self.units = 'MM'
  1192. # coordinates for relative position display
  1193. self.rel_point1 = (0, 0)
  1194. self.rel_point2 = (0, 0)
  1195. # variable to store coordinates
  1196. self.pos = (0, 0)
  1197. self.pos_canvas = (0, 0)
  1198. self.pos_jump = (0, 0)
  1199. # variable to store mouse coordinates
  1200. self.mouse = [0, 0]
  1201. # variable to store the delta positions on cavnas
  1202. self.dx = 0
  1203. self.dy = 0
  1204. # decide if we have a double click or single click
  1205. self.doubleclick = False
  1206. # store here the is_dragging value
  1207. self.event_is_dragging = False
  1208. # variable to store if a command is active (then the var is not None) and which one it is
  1209. self.command_active = None
  1210. # variable to store the status of moving selection action
  1211. # None value means that it's not an selection action
  1212. # True value = a selection from left to right
  1213. # False value = a selection from right to left
  1214. self.selection_type = None
  1215. # List to store the objects that are currently loaded in FlatCAM
  1216. # This list is updated on each object creation or object delete
  1217. self.all_objects_list = []
  1218. self.objects_under_the_click_list = []
  1219. # List to store the objects that are selected
  1220. self.sel_objects_list = []
  1221. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1222. self.key_modifiers = None
  1223. # Variable to hold the status of the axis
  1224. self.toggle_axis = True
  1225. # Variable to hold the status of the grid lines
  1226. self.toggle_grid_lines = True
  1227. # Variable to store the status of the code editor
  1228. self.toggle_codeeditor = False
  1229. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1230. self.click_noproject = False
  1231. self.cursor = None
  1232. # Variable to store the GCODE that was edited
  1233. self.gcode_edited = ""
  1234. self.text_editor_tab = None
  1235. # reference for the self.ui.code_editor
  1236. self.reference_code_editor = None
  1237. self.script_code = ''
  1238. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1239. self.tools_db_changed_flag = False
  1240. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1241. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1242. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1243. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1244. 'tsm']
  1245. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1246. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1247. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1248. 'sbp', 'tap', 'xpi']
  1249. self.svg_list = ['svg']
  1250. self.dxf_list = ['dxf']
  1251. self.pdf_list = ['pdf']
  1252. self.prj_list = ['flatprj']
  1253. self.conf_list = ['flatconfig']
  1254. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1255. # flag for polygons not cleared
  1256. self.poly_not_cleared = False
  1257. # VisPy visuals
  1258. self.isHovering = False
  1259. self.notHovering = True
  1260. # Window geometry
  1261. self.x_pos = None
  1262. self.y_pos = None
  1263. self.width = None
  1264. self.height = None
  1265. # when True, the app has to return from any thread
  1266. self.abort_flag = False
  1267. # set the value used in the Windows Title
  1268. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1269. # this holds a widget that is installed in the Plot Area when View Source option is used
  1270. self.source_editor_tab = None
  1271. self.pagesize = {}
  1272. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1273. # VisPy visuals
  1274. if self.is_legacy is False:
  1275. try:
  1276. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1277. except AttributeError:
  1278. self.tool_shapes = None
  1279. else:
  1280. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1281. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1282. # used in the delayed shutdown self.start_delayed_quit() method
  1283. self.save_timer = None
  1284. # ###########################################################################################################
  1285. # ################################## ADDING FlatCAM EDITORS section #########################################
  1286. # ###########################################################################################################
  1287. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1288. # at the first launch of the App , the editors will not be functional.
  1289. try:
  1290. self.geo_editor = FlatCAMGeoEditor(self)
  1291. except AttributeError:
  1292. pass
  1293. try:
  1294. self.exc_editor = FlatCAMExcEditor(self)
  1295. except AttributeError:
  1296. pass
  1297. try:
  1298. self.grb_editor = FlatCAMGrbEditor(self)
  1299. except AttributeError:
  1300. pass
  1301. self.log.debug("Finished adding FlatCAM Editor's.")
  1302. self.set_ui_title(name=_("New Project - Not saved"))
  1303. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1304. current_platform = platform.architecture()[0]
  1305. if current_platform != '64bit':
  1306. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1307. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1308. # ###########################################################################################################
  1309. # ########################################### EXCLUSION AREAS ###############################################
  1310. # ###########################################################################################################
  1311. self.exc_areas = ExclusionAreas(app=self)
  1312. # ###########################################################################################################
  1313. # ##################################### Finished the CONSTRUCTOR ############################################
  1314. # ###########################################################################################################
  1315. App.log.debug("END of constructor. Releasing control.")
  1316. # ###########################################################################################################
  1317. # ########################################## SHOW AppGUI #######################################################
  1318. # ###########################################################################################################
  1319. # if the app is not started as headless, show it
  1320. if self.cmd_line_headless != 1:
  1321. if show_splash:
  1322. # finish the splash
  1323. self.splash.finish(self.ui)
  1324. mgui_settings = QSettings("Open Source", "FlatCAM")
  1325. if mgui_settings.contains("maximized_gui"):
  1326. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1327. if maximized_ui is True:
  1328. self.ui.showMaximized()
  1329. else:
  1330. self.ui.show()
  1331. else:
  1332. self.ui.show()
  1333. if self.defaults["global_systray_icon"]:
  1334. self.trayIcon.show()
  1335. else:
  1336. log.warning("******************* RUNNING HEADLESS *******************")
  1337. # ###########################################################################################################
  1338. # ######################################## START-UP ARGUMENTS ###############################################
  1339. # ###########################################################################################################
  1340. # test if the program was started with a script as parameter
  1341. if self.cmd_line_shellvar:
  1342. try:
  1343. cnt = 0
  1344. command_tcl = 0
  1345. for i in self.cmd_line_shellvar.split(','):
  1346. if i is not None:
  1347. # noinspection PyBroadException
  1348. try:
  1349. command_tcl = eval(i)
  1350. except Exception:
  1351. command_tcl = i
  1352. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1353. cnt += 1
  1354. # if there are Windows paths then replace the path separator with a Unix like one
  1355. if sys.platform == 'win32':
  1356. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1357. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1358. except Exception as ext:
  1359. print("ERROR: ", ext)
  1360. sys.exit(2)
  1361. if self.cmd_line_shellfile:
  1362. if self.cmd_line_headless != 1:
  1363. if self.ui.shell_dock.isHidden():
  1364. self.ui.shell_dock.show()
  1365. try:
  1366. with open(self.cmd_line_shellfile, "r") as myfile:
  1367. # if show_splash:
  1368. # self.splash.showMessage('%s: %ssec\n%s' % (
  1369. # _("Canvas initialization started.\n"
  1370. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1371. # _("Executing Tcl Script ...")),
  1372. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1373. # color=QtGui.QColor("gray"))
  1374. cmd_line_shellfile_text = myfile.read()
  1375. if self.cmd_line_headless != 1:
  1376. self.shell.exec_command(cmd_line_shellfile_text)
  1377. else:
  1378. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1379. except Exception as ext:
  1380. print("ERROR: ", ext)
  1381. sys.exit(2)
  1382. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1383. # the path/file_name must be enclosed in quotes if it contain spaces
  1384. if App.args:
  1385. self.args_at_startup.emit(App.args)
  1386. if self.defaults.old_defaults_found is True:
  1387. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1388. "Please reboot the application to update."))
  1389. self.defaults.old_defaults_found = False
  1390. # ######################################### INIT FINISHED #######################################################
  1391. # #################################################################################################################
  1392. # #################################################################################################################
  1393. # #################################################################################################################
  1394. # #################################################################################################################
  1395. # #################################################################################################################
  1396. @staticmethod
  1397. def copy_and_overwrite(from_path, to_path):
  1398. """
  1399. From here:
  1400. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1401. :param from_path: source path
  1402. :param to_path: destination path
  1403. :return: None
  1404. """
  1405. if os.path.exists(to_path):
  1406. shutil.rmtree(to_path)
  1407. try:
  1408. shutil.copytree(from_path, to_path)
  1409. except FileNotFoundError:
  1410. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1411. shutil.copytree(from_new_path, to_path)
  1412. def on_startup_args(self, args, silent=False):
  1413. """
  1414. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1415. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1416. :param args: a list containing the application args at startup
  1417. :return: None
  1418. """
  1419. if args is not None:
  1420. args_to_process = args
  1421. else:
  1422. args_to_process = App.args
  1423. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1424. for argument in args_to_process:
  1425. if '.FlatPrj'.lower() in argument.lower():
  1426. try:
  1427. project_name = str(argument)
  1428. if project_name == "":
  1429. if silent is False:
  1430. self.inform.emit(_("Cancelled."))
  1431. else:
  1432. # self.open_project(project_name)
  1433. run_from_arg = True
  1434. # self.worker_task.emit({'fcn': self.open_project,
  1435. # 'params': [project_name, run_from_arg]})
  1436. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1437. except Exception as e:
  1438. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1439. elif '.FlatConfig'.lower() in argument.lower():
  1440. try:
  1441. file_name = str(argument)
  1442. if file_name == "":
  1443. if silent is False:
  1444. self.inform.emit(_("Open Config file failed."))
  1445. else:
  1446. run_from_arg = True
  1447. # self.worker_task.emit({'fcn': self.open_config_file,
  1448. # 'params': [file_name, run_from_arg]})
  1449. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1450. except Exception as e:
  1451. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1452. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1453. try:
  1454. file_name = str(argument)
  1455. if file_name == "":
  1456. if silent is False:
  1457. self.inform.emit(_("Open Script file failed."))
  1458. else:
  1459. if silent is False:
  1460. self.on_fileopenscript(name=file_name)
  1461. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1462. self.on_filerunscript(name=file_name)
  1463. except Exception as e:
  1464. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1465. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1466. log.debug("App.on_startup_args() --> Quit event.")
  1467. sys.exit()
  1468. elif 'save'.lower() in argument.lower():
  1469. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1470. self.preferencesUiManager.save_defaults()
  1471. else:
  1472. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1473. proc_arg = argument.lower()
  1474. for ext in exc_list:
  1475. proc_ext = ext.replace(' ', '')
  1476. proc_ext = '.%s' % proc_ext
  1477. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1478. file_name = str(argument)
  1479. if file_name == "":
  1480. if silent is False:
  1481. self.inform.emit(_("Open Excellon file failed."))
  1482. else:
  1483. self.on_fileopenexcellon(name=file_name, signal=None)
  1484. return
  1485. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1486. for ext in gco_list:
  1487. proc_ext = ext.replace(' ', '')
  1488. proc_ext = '.%s' % proc_ext
  1489. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1490. file_name = str(argument)
  1491. if file_name == "":
  1492. if silent is False:
  1493. self.inform.emit(_("Open GCode file failed."))
  1494. else:
  1495. self.on_fileopengcode(name=file_name, signal=None)
  1496. return
  1497. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1498. for ext in grb_list:
  1499. proc_ext = ext.replace(' ', '')
  1500. proc_ext = '.%s' % proc_ext
  1501. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1502. file_name = str(argument)
  1503. if file_name == "":
  1504. if silent is False:
  1505. self.inform.emit(_("Open Gerber file failed."))
  1506. else:
  1507. self.on_fileopengerber(name=file_name, signal=None)
  1508. return
  1509. # if it reached here without already returning then the app was registered with a file that it does not
  1510. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1511. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1512. # for arg in args_to_process:
  1513. # if 'FlatCAM.exe' in arg:
  1514. # continue
  1515. # else:
  1516. # sys.exit(2)
  1517. def set_ui_title(self, name):
  1518. """
  1519. Sets the title of the main window.
  1520. :param name: String that store the project path and project name
  1521. :return: None
  1522. """
  1523. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1524. (self.version,
  1525. ('BETA' if self.beta else ''),
  1526. platform.architecture()[0],
  1527. self.engine,
  1528. name)
  1529. )
  1530. def on_app_restart(self):
  1531. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1532. # be left in the SySTray
  1533. try:
  1534. self.trayIcon.hide()
  1535. except Exception:
  1536. pass
  1537. fcTranslate.restart_program(app=self)
  1538. def clear_pool(self):
  1539. """
  1540. Clear the multiprocessing pool and calls garbage collector.
  1541. :return: None
  1542. """
  1543. self.pool.close()
  1544. self.pool = Pool()
  1545. self.pool_recreated.emit(self.pool)
  1546. gc.collect()
  1547. def install_tools(self):
  1548. """
  1549. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1550. Instantiation of the Tools classes.
  1551. The order that the tools are installed is important as they can depend on each other install position.
  1552. :return: None
  1553. """
  1554. self.distance_tool = Distance(self)
  1555. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1556. before=self.ui.menueditorigin,
  1557. separator=False)
  1558. self.distance_min_tool = DistanceMin(self)
  1559. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1560. pos=self.ui.menuedit,
  1561. before=self.ui.menueditorigin,
  1562. separator=True)
  1563. self.dblsidedtool = DblSidedTool(self)
  1564. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1565. self.cal_exc_tool = ToolCalibration(self)
  1566. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1567. before=self.dblsidedtool.menuAction,
  1568. separator=False)
  1569. self.align_objects_tool = AlignObjects(self)
  1570. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1571. self.edrills_tool = ToolExtractDrills(self)
  1572. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1573. self.panelize_tool = Panelize(self)
  1574. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1575. self.film_tool = Film(self)
  1576. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1577. self.paste_tool = SolderPaste(self)
  1578. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1579. self.calculator_tool = ToolCalculator(self)
  1580. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1581. self.sub_tool = ToolSub(self)
  1582. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1583. pos=self.ui.menutool, separator=True)
  1584. self.rules_tool = RulesCheck(self)
  1585. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1586. pos=self.ui.menutool, separator=False)
  1587. self.optimal_tool = ToolOptimal(self)
  1588. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1589. pos=self.ui.menutool, separator=True)
  1590. self.move_tool = ToolMove(self)
  1591. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1592. before=self.ui.menueditorigin, separator=True)
  1593. self.cutout_tool = CutOut(self)
  1594. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1595. before=self.sub_tool.menuAction)
  1596. self.ncclear_tool = NonCopperClear(self)
  1597. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1598. before=self.sub_tool.menuAction, separator=True)
  1599. self.paint_tool = ToolPaint(self)
  1600. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1601. before=self.sub_tool.menuAction, separator=True)
  1602. self.copper_thieving_tool = ToolCopperThieving(self)
  1603. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1604. pos=self.ui.menutool)
  1605. self.fiducial_tool = ToolFiducials(self)
  1606. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1607. pos=self.ui.menutool)
  1608. self.qrcode_tool = QRCode(self)
  1609. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1610. pos=self.ui.menutool)
  1611. self.punch_tool = ToolPunchGerber(self)
  1612. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1613. self.invert_tool = ToolInvertGerber(self)
  1614. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1615. self.corners_tool = ToolCorners(self)
  1616. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1617. self.transform_tool = ToolTransform(self)
  1618. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1619. pos=self.ui.menuoptions, separator=True)
  1620. self.properties_tool = Properties(self)
  1621. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1622. pos=self.ui.menuoptions)
  1623. self.pdf_tool = ToolPDF(self)
  1624. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1625. pos=self.ui.menufileimport,
  1626. separator=True)
  1627. self.image_tool = ToolImage(self)
  1628. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1629. pos=self.ui.menufileimport,
  1630. separator=True)
  1631. self.pcb_wizard_tool = PcbWizard(self)
  1632. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1633. pos=self.ui.menufileimport)
  1634. self.log.debug("Tools are installed.")
  1635. def remove_tools(self):
  1636. """
  1637. Will remove all the actions in the Tool menu.
  1638. :return: None
  1639. """
  1640. for act in self.ui.menutool.actions():
  1641. self.ui.menutool.removeAction(act)
  1642. def init_tools(self):
  1643. """
  1644. Initialize the Tool tab in the notebook side of the central widget.
  1645. Remove the actions in the Tools menu.
  1646. Instantiate again the FlatCAM tools (plugins).
  1647. All this is required when changing the layout: standard, compact etc.
  1648. :return: None
  1649. """
  1650. log.debug("init_tools()")
  1651. # delete the data currently in the Tools Tab and the Tab itself
  1652. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1653. if widget is not None:
  1654. widget.deleteLater()
  1655. self.ui.notebook.removeTab(2)
  1656. # rebuild the Tools Tab
  1657. self.ui.tool_tab = QtWidgets.QWidget()
  1658. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1659. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1660. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1661. self.ui.tool_scroll_area = VerticalScrollArea()
  1662. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1663. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1664. # first remove all of them
  1665. self.remove_tools()
  1666. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1667. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1668. '&Command Line\tS')
  1669. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1670. # third install all of them
  1671. try:
  1672. self.install_tools()
  1673. except AttributeError:
  1674. pass
  1675. self.log.debug("Tools are initialized.")
  1676. # def parse_system_fonts(self):
  1677. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1678. # 'params': []})
  1679. def connect_toolbar_signals(self):
  1680. """
  1681. Reconnect the signals to the actions in the toolbar.
  1682. This has to be done each time after the FlatCAM tools are removed/installed.
  1683. :return: None
  1684. """
  1685. # Toolbar
  1686. # File Toolbar Signals
  1687. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1688. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1689. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1690. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1691. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1692. # View Toolbar Signals
  1693. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1694. self.ui.replot_btn.triggered.connect(self.plot_all)
  1695. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1696. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1697. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1698. # Edit Toolbar Signals
  1699. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1700. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1701. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1702. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1703. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1704. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1705. self.ui.delete_btn.triggered.connect(self.on_delete)
  1706. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1707. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1708. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1709. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1710. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1711. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1712. # Scripting Toolbar Signals
  1713. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1714. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1715. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1716. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1717. # Tools Toolbar Signals
  1718. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1719. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1720. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1721. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1722. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1723. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1724. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1725. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1726. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1727. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1728. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1729. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1730. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1731. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1732. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1733. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1734. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1735. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1736. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1737. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1738. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1739. def object2editor(self):
  1740. """
  1741. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1742. :return: None
  1743. """
  1744. self.defaults.report_usage("object2editor()")
  1745. # disable the objects menu as it may interfere with the AppEditors
  1746. self.ui.menuobjects.setDisabled(True)
  1747. edited_object = self.collection.get_active()
  1748. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1749. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1750. pass
  1751. else:
  1752. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1753. return
  1754. if isinstance(edited_object, GeometryObject):
  1755. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1756. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1757. # we set the notebook to hidden
  1758. # self.ui.splitter.setSizes([0, 1])
  1759. if edited_object.multigeo is True:
  1760. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1761. if len(sel_rows) > 1:
  1762. self.inform.emit('[WARNING_NOTCL] %s' %
  1763. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1764. "is not possible.\n"
  1765. "Edit only one geometry at a time."))
  1766. # determine the tool dia of the selected tool
  1767. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1768. # now find the key in the edited_object.tools that has this tooldia
  1769. multi_tool = 1
  1770. for tool in edited_object.tools:
  1771. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1772. multi_tool = tool
  1773. break
  1774. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1775. else:
  1776. self.geo_editor.edit_fcgeometry(edited_object)
  1777. # set call source to the Editor we go into
  1778. self.call_source = 'geo_editor'
  1779. elif isinstance(edited_object, ExcellonObject):
  1780. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1781. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1782. if self.ui.splitter.sizes()[0] == 0:
  1783. self.ui.splitter.setSizes([1, 1])
  1784. self.exc_editor.edit_fcexcellon(edited_object)
  1785. # set call source to the Editor we go into
  1786. self.call_source = 'exc_editor'
  1787. elif isinstance(edited_object, GerberObject):
  1788. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1789. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1790. if self.ui.splitter.sizes()[0] == 0:
  1791. self.ui.splitter.setSizes([1, 1])
  1792. self.grb_editor.edit_fcgerber(edited_object)
  1793. # set call source to the Editor we go into
  1794. self.call_source = 'grb_editor'
  1795. # reset the following variables so the UI is built again after edit
  1796. edited_object.ui_build = False
  1797. edited_object.build_aperture_storage = False
  1798. elif isinstance(edited_object, CNCJobObject):
  1799. if self.ui.splitter.sizes()[0] == 0:
  1800. self.ui.splitter.setSizes([1, 1])
  1801. edited_object.on_edit_code_click()
  1802. return
  1803. # make sure that we can't select another object while in Editor Mode:
  1804. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1805. self.ui.project_frame.setDisabled(True)
  1806. # delete any selection shape that might be active as they are not relevant in Editor
  1807. self.delete_selection_shape()
  1808. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1809. self.ui.plot_tab_area.protectTab(0)
  1810. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1811. self.should_we_save = True
  1812. def editor2object(self, cleanup=None):
  1813. """
  1814. Transfers the Geometry or Excellon from it's editor to the current object.
  1815. :return: None
  1816. """
  1817. self.defaults.report_usage("editor2object()")
  1818. # re-enable the objects menu that was disabled on entry in Editor mode
  1819. self.ui.menuobjects.setDisabled(False)
  1820. # do not update a geometry or excellon object unless it comes out of an editor
  1821. if self.call_source != 'app':
  1822. edited_obj = self.collection.get_active()
  1823. if cleanup is None:
  1824. msgbox = QtWidgets.QMessageBox()
  1825. msgbox.setText(_("Do you want to save the edited object?"))
  1826. msgbox.setWindowTitle(_("Close Editor"))
  1827. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1828. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1829. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1830. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1831. msgbox.setDefaultButton(bt_yes)
  1832. msgbox.exec_()
  1833. response = msgbox.clickedButton()
  1834. if response == bt_yes:
  1835. # clean the Tools Tab
  1836. self.ui.tool_scroll_area.takeWidget()
  1837. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1838. self.ui.notebook.setTabText(2, "Tool")
  1839. if isinstance(edited_obj, GeometryObject):
  1840. obj_type = "Geometry"
  1841. if cleanup is None:
  1842. self.geo_editor.update_fcgeometry(edited_obj)
  1843. # self.geo_editor.update_options(edited_obj)
  1844. self.geo_editor.deactivate()
  1845. # restore AppGUI to the Selected TAB
  1846. # Remove anything else in the AppGUI
  1847. self.ui.tool_scroll_area.takeWidget()
  1848. # update the geo object options so it is including the bounding box values
  1849. try:
  1850. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1851. edited_obj.options['xmin'] = xmin
  1852. edited_obj.options['ymin'] = ymin
  1853. edited_obj.options['xmax'] = xmax
  1854. edited_obj.options['ymax'] = ymax
  1855. except AttributeError as e:
  1856. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1857. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1858. edited_obj.build_ui()
  1859. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1860. elif isinstance(edited_obj, GerberObject):
  1861. obj_type = "Gerber"
  1862. if cleanup is None:
  1863. self.grb_editor.update_fcgerber()
  1864. self.grb_editor.update_options(edited_obj)
  1865. self.grb_editor.deactivate_grb_editor()
  1866. # delete the old object (the source object) if it was an empty one
  1867. try:
  1868. if len(edited_obj.solid_geometry) == 0:
  1869. old_name = edited_obj.options['name']
  1870. self.collection.set_active(old_name)
  1871. self.collection.delete_active()
  1872. except TypeError:
  1873. # if the solid_geometry is a single Polygon the len() will not work
  1874. # in any case, falling here means that we have something in the solid_geometry, even if only
  1875. # a single Polygon, therefore we pass this
  1876. pass
  1877. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1878. # restore AppGUI to the Selected TAB
  1879. # Remove anything else in the AppGUI
  1880. self.ui.selected_scroll_area.takeWidget()
  1881. elif isinstance(edited_obj, ExcellonObject):
  1882. obj_type = "Excellon"
  1883. if cleanup is None:
  1884. self.exc_editor.update_fcexcellon(edited_obj)
  1885. # self.exc_editor.update_options(edited_obj)
  1886. self.exc_editor.deactivate()
  1887. # restore AppGUI to the Selected TAB
  1888. # Remove anything else in the AppGUI
  1889. self.ui.tool_scroll_area.takeWidget()
  1890. # delete the old object (the source object) if it was an empty one
  1891. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1892. old_name = edited_obj.options['name']
  1893. self.collection.delete_by_name(name=old_name)
  1894. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1895. else:
  1896. self.inform.emit('[WARNING_NOTCL] %s' %
  1897. _("Select a Gerber, Geometry or Excellon Object to update."))
  1898. return
  1899. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1900. elif response == bt_no:
  1901. # clean the Tools Tab
  1902. self.ui.tool_scroll_area.takeWidget()
  1903. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1904. self.ui.notebook.setTabText(2, "Tool")
  1905. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1906. if isinstance(edited_obj, GeometryObject):
  1907. self.geo_editor.deactivate()
  1908. edited_obj.build_ui()
  1909. elif isinstance(edited_obj, GerberObject):
  1910. self.grb_editor.deactivate_grb_editor()
  1911. edited_obj.build_ui()
  1912. elif isinstance(edited_obj, ExcellonObject):
  1913. self.exc_editor.deactivate()
  1914. edited_obj.build_ui()
  1915. else:
  1916. self.inform.emit('[WARNING_NOTCL] %s' %
  1917. _("Select a Gerber, Geometry or Excellon Object to update."))
  1918. return
  1919. elif response == bt_cancel:
  1920. return
  1921. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1922. # edited_obj.build_ui()
  1923. # Switch notebook to Selected page
  1924. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1925. else:
  1926. if isinstance(edited_obj, GeometryObject):
  1927. self.geo_editor.deactivate()
  1928. elif isinstance(edited_obj, GerberObject):
  1929. self.grb_editor.deactivate_grb_editor()
  1930. elif isinstance(edited_obj, ExcellonObject):
  1931. self.exc_editor.deactivate()
  1932. else:
  1933. self.inform.emit('[WARNING_NOTCL] %s' %
  1934. _("Select a Gerber, Geometry or Excellon Object to update."))
  1935. return
  1936. # if notebook is hidden we show it
  1937. if self.ui.splitter.sizes()[0] == 0:
  1938. self.ui.splitter.setSizes([1, 1])
  1939. # restore the call_source to app
  1940. self.call_source = 'app'
  1941. edited_obj.plot()
  1942. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1943. self.ui.plot_tab_area.protectTab(0)
  1944. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1945. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1946. self.ui.project_frame.setDisabled(False)
  1947. def get_last_folder(self):
  1948. """
  1949. Get the folder path from where the last file was opened.
  1950. :return: String, last opened folder path
  1951. """
  1952. return self.defaults["global_last_folder"]
  1953. def get_last_save_folder(self):
  1954. """
  1955. Get the folder path from where the last file was saved.
  1956. :return: String, last saved folder path
  1957. """
  1958. loc = self.defaults["global_last_save_folder"]
  1959. if loc is None:
  1960. loc = self.defaults["global_last_folder"]
  1961. if loc is None:
  1962. loc = os.path.dirname(__file__)
  1963. return loc
  1964. def info(self, msg):
  1965. """
  1966. Informs the user. Normally on the status bar, optionally
  1967. also on the shell.
  1968. :param msg: Text to write.
  1969. :return: None
  1970. """
  1971. # Type of message in brackets at the beginning of the message.
  1972. match = re.search(r"\[(.*)\](.*)", msg)
  1973. if match:
  1974. level = match.group(1)
  1975. msg_ = match.group(2)
  1976. self.ui.fcinfo.set_status(str(msg_), level=level)
  1977. if level.lower() == "error":
  1978. self.shell_message(msg, error=True, show=True)
  1979. elif level.lower() == "warning":
  1980. self.shell_message(msg, warning=True, show=True)
  1981. elif level.lower() == "error_notcl":
  1982. self.shell_message(msg, error=True, show=False)
  1983. elif level.lower() == "warning_notcl":
  1984. self.shell_message(msg, warning=True, show=False)
  1985. elif level.lower() == "success":
  1986. self.shell_message(msg, success=True, show=False)
  1987. elif level.lower() == "selected":
  1988. self.shell_message(msg, selected=True, show=False)
  1989. else:
  1990. self.shell_message(msg, show=False)
  1991. else:
  1992. self.ui.fcinfo.set_status(str(msg), level="info")
  1993. # make sure that if the message is to clear the infobar with a space
  1994. # is not printed over and over on the shell
  1995. if msg != '':
  1996. self.shell_message(msg)
  1997. def on_import_preferences(self):
  1998. """
  1999. Loads the application default settings from a saved file into
  2000. ``self.defaults`` dictionary.
  2001. :return: None
  2002. """
  2003. self.defaults.report_usage("on_import_preferences")
  2004. App.log.debug("App.on_import_preferences()")
  2005. # Show file chooser
  2006. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2007. try:
  2008. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2009. directory=self.data_path,
  2010. filter=filter_)
  2011. except TypeError:
  2012. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2013. filter=filter_)
  2014. filename = str(filename)
  2015. if filename == "":
  2016. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2017. return
  2018. # Load in the defaults from the chosen file
  2019. self.defaults.load(filename=filename)
  2020. self.preferencesUiManager.on_preferences_edited()
  2021. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2022. def on_export_preferences(self):
  2023. """
  2024. Save the defaults dictionary to a file.
  2025. :return: None
  2026. """
  2027. self.defaults.report_usage("on_export_preferences")
  2028. App.log.debug("on_export_preferences()")
  2029. # defaults_file_content = None
  2030. # Show file chooser
  2031. date = str(datetime.today()).rpartition('.')[0]
  2032. date = ''.join(c for c in date if c not in ':-')
  2033. date = date.replace(' ', '_')
  2034. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2035. try:
  2036. filename, _f = FCFileSaveDialog.get_saved_filename(
  2037. caption=_("Export FlatCAM Preferences"),
  2038. directory=self.data_path + '/preferences_' + date,
  2039. filter=filter__
  2040. )
  2041. except TypeError:
  2042. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2043. filename = str(filename)
  2044. if filename == "":
  2045. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2046. return
  2047. # Update options
  2048. self.preferencesUiManager.defaults_read_form()
  2049. self.defaults.propagate_defaults()
  2050. # Save update options
  2051. try:
  2052. self.defaults.write(filename=filename)
  2053. except Exception:
  2054. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2055. return
  2056. if self.defaults["global_open_style"] is False:
  2057. self.file_opened.emit("preferences", filename)
  2058. self.file_saved.emit("preferences", filename)
  2059. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2060. def save_to_file(self, content_to_save, txt_content):
  2061. """
  2062. Save something to a file.
  2063. :return: None
  2064. """
  2065. self.defaults.report_usage("save_to_file")
  2066. App.log.debug("save_to_file()")
  2067. self.date = str(datetime.today()).rpartition('.')[0]
  2068. self.date = ''.join(c for c in self.date if c not in ':-')
  2069. self.date = self.date.replace(' ', '_')
  2070. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2071. path_to_save = self.defaults["global_last_save_folder"] if \
  2072. self.defaults["global_last_save_folder"] is not None else self.data_path
  2073. try:
  2074. filename, _f = FCFileSaveDialog.get_saved_filename(
  2075. caption=_("Save to file"),
  2076. directory=path_to_save + '/file_' + self.date,
  2077. filter=filter__
  2078. )
  2079. except TypeError:
  2080. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2081. filename = str(filename)
  2082. if filename == "":
  2083. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2084. return
  2085. else:
  2086. try:
  2087. with open(filename, 'w') as f:
  2088. ___ = f.read()
  2089. except PermissionError:
  2090. self.inform.emit('[WARNING] %s' %
  2091. _("Permission denied, saving not possible.\n"
  2092. "Most likely another app is holding the file open and not accessible."))
  2093. return
  2094. except IOError:
  2095. App.log.debug('Creating a new file ...')
  2096. f = open(filename, 'w')
  2097. f.close()
  2098. except Exception:
  2099. e = sys.exc_info()[0]
  2100. App.log.error("Could not load the file.")
  2101. App.log.error(str(e))
  2102. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2103. return
  2104. # Save content
  2105. if filename.rpartition('.')[2].lower() == 'html':
  2106. file_content = content_to_save
  2107. else:
  2108. file_content = txt_content
  2109. try:
  2110. with open(filename, "w") as f:
  2111. f.write(file_content)
  2112. except Exception:
  2113. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2114. return
  2115. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2116. def save_geometry(self, x, y, width, height, notebook_width):
  2117. """
  2118. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2119. launch of the application.
  2120. :param x: X position of the main window
  2121. :param y: Y position of the main window
  2122. :param width: width of the main window
  2123. :param height: height of the main window
  2124. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2125. :return: None
  2126. """
  2127. self.defaults["global_def_win_x"] = x
  2128. self.defaults["global_def_win_y"] = y
  2129. self.defaults["global_def_win_w"] = width
  2130. self.defaults["global_def_win_h"] = height
  2131. self.defaults["global_def_notebook_width"] = notebook_width
  2132. self.preferencesUiManager.save_defaults()
  2133. def register_recent(self, kind, filename):
  2134. """
  2135. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2136. dictionary.
  2137. :param kind: type of file that was opened
  2138. :param filename: the path and file name for the file that was opened
  2139. :return:
  2140. """
  2141. self.log.debug("register_recent()")
  2142. self.log.debug(" %s" % kind)
  2143. self.log.debug(" %s" % filename)
  2144. record = {'kind': str(kind), 'filename': str(filename)}
  2145. if record in self.recent:
  2146. return
  2147. if record in self.recent_projects:
  2148. return
  2149. if record['kind'] == 'project':
  2150. self.recent_projects.insert(0, record)
  2151. else:
  2152. self.recent.insert(0, record)
  2153. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2154. self.recent.pop()
  2155. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2156. self.recent_projects.pop()
  2157. try:
  2158. f = open(self.data_path + '/recent.json', 'w')
  2159. except IOError:
  2160. App.log.error("Failed to open recent items file for writing.")
  2161. self.inform.emit('[ERROR_NOTCL] %s' %
  2162. _('Failed to open recent files file for writing.'))
  2163. return
  2164. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2165. f.close()
  2166. try:
  2167. fp = open(self.data_path + '/recent_projects.json', 'w')
  2168. except IOError:
  2169. App.log.error("Failed to open recent items file for writing.")
  2170. self.inform.emit('[ERROR_NOTCL] %s' %
  2171. _('Failed to open recent projects file for writing.'))
  2172. return
  2173. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2174. fp.close()
  2175. # Re-build the recent items menu
  2176. self.setup_recent_items()
  2177. def new_object(self, kind, name, initialize, plot=True, autoselected=True):
  2178. """
  2179. Creates a new specialized FlatCAMObj and attaches it to the application,
  2180. this is, updates the AppGUI accordingly, any other records and plots it.
  2181. This method is thread-safe.
  2182. Notes:
  2183. * If the name is in use, the self.collection will modify it
  2184. when appending it to the collection. There is no need to handle
  2185. name conflicts here.
  2186. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2187. :type kind: str
  2188. :param name: Name for the object.
  2189. :type name: str
  2190. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2191. The function is called with 2 parameters: the new object and the App instance.
  2192. :type initialize: function
  2193. :param plot: If to plot the resulting object
  2194. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2195. self.collection
  2196. :return: None
  2197. :rtype: None
  2198. """
  2199. App.log.debug("new_object()")
  2200. obj_plot = plot
  2201. obj_autoselected = autoselected
  2202. t0 = time.time() # Debug
  2203. # ## Create object
  2204. classdict = {
  2205. "gerber": GerberObject,
  2206. "excellon": ExcellonObject,
  2207. "cncjob": CNCJobObject,
  2208. "geometry": GeometryObject,
  2209. "script": ScriptObject,
  2210. "document": DocumentObject
  2211. }
  2212. App.log.debug("Calling object constructor...")
  2213. # Object creation/instantiation
  2214. obj = classdict[kind](name)
  2215. obj.units = self.options["units"]
  2216. # IMPORTANT
  2217. # The key names in defaults and options dictionary's are not random:
  2218. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2219. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2220. # copied to self.options. After that, below, depending on the type of
  2221. # object that is created, it will strip the name of the object and the underline (if the original key was
  2222. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2223. # "toolchange"
  2224. for option in self.options:
  2225. if option.find(kind + "_") == 0:
  2226. oname = option[len(kind) + 1:]
  2227. obj.options[oname] = self.options[option]
  2228. obj.isHovering = False
  2229. obj.notHovering = True
  2230. # Initialize as per user request
  2231. # User must take care to implement initialize
  2232. # in a thread-safe way as is is likely that we
  2233. # have been invoked in a separate thread.
  2234. t1 = time.time()
  2235. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2236. try:
  2237. return_value = initialize(obj, self)
  2238. except Exception as e:
  2239. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2240. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2241. msg += traceback.format_exc()
  2242. self.inform.emit(msg)
  2243. return "fail"
  2244. t2 = time.time()
  2245. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2246. if return_value == 'fail':
  2247. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2248. return "fail"
  2249. # Check units and convert if necessary
  2250. # This condition CAN be true because initialize() can change obj.units
  2251. if self.options["units"].upper() != obj.units.upper():
  2252. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2253. obj.convert_units(self.options["units"])
  2254. t3 = time.time()
  2255. self.log.debug("%f seconds converting units." % (t3 - t2))
  2256. # Create the bounding box for the object and then add the results to the obj.options
  2257. # But not for Scripts or for Documents
  2258. if kind != 'document' and kind != 'script':
  2259. try:
  2260. xmin, ymin, xmax, ymax = obj.bounds()
  2261. obj.options['xmin'] = xmin
  2262. obj.options['ymin'] = ymin
  2263. obj.options['xmax'] = xmax
  2264. obj.options['ymax'] = ymax
  2265. except Exception as e:
  2266. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2267. return "fail"
  2268. try:
  2269. if kind == 'excellon':
  2270. obj.fill_color = self.defaults["excellon_plot_fill"]
  2271. obj.outline_color = self.defaults["excellon_plot_line"]
  2272. if kind == 'gerber':
  2273. obj.fill_color = self.defaults["gerber_plot_fill"]
  2274. obj.outline_color = self.defaults["gerber_plot_line"]
  2275. except Exception as e:
  2276. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2277. # update the KeyWords list with the name of the file
  2278. self.myKeywords.append(obj.options['name'])
  2279. log.debug("Moving new object back to main thread.")
  2280. # Move the object to the main thread and let the app know that it is available.
  2281. obj.moveToThread(self.main_thread)
  2282. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2283. return obj
  2284. def new_excellon_object(self):
  2285. """
  2286. Creates a new, blank Excellon object.
  2287. :return: None
  2288. """
  2289. self.defaults.report_usage("new_excellon_object()")
  2290. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2291. def new_geometry_object(self):
  2292. """
  2293. Creates a new, blank and single-tool Geometry object.
  2294. :return: None
  2295. """
  2296. self.defaults.report_usage("new_geometry_object()")
  2297. def initialize(obj, app):
  2298. obj.multitool = False
  2299. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2300. def new_gerber_object(self):
  2301. """
  2302. Creates a new, blank Gerber object.
  2303. :return: None
  2304. """
  2305. self.defaults.report_usage("new_gerber_object()")
  2306. def initialize(grb_obj, app):
  2307. grb_obj.multitool = False
  2308. grb_obj.source_file = []
  2309. grb_obj.multigeo = False
  2310. grb_obj.follow = False
  2311. grb_obj.apertures = {}
  2312. grb_obj.solid_geometry = []
  2313. try:
  2314. grb_obj.options['xmin'] = 0
  2315. grb_obj.options['ymin'] = 0
  2316. grb_obj.options['xmax'] = 0
  2317. grb_obj.options['ymax'] = 0
  2318. except KeyError:
  2319. pass
  2320. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2321. def new_script_object(self):
  2322. """
  2323. Creates a new, blank TCL Script object.
  2324. :return: None
  2325. """
  2326. self.defaults.report_usage("new_script_object()")
  2327. # commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2328. # "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2329. # "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2330. # "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2331. # "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2332. # "ListSys, MillDrills,\n" \
  2333. # "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2334. # "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2335. # "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2336. # "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2337. # "# SubtractRectangle, Version, WriteGCode\n"
  2338. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2339. '# %s:\n' % _('TCL Tutorial is here') + \
  2340. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2341. '# %s:\n' % _("FlatCAM commands list")
  2342. new_source_file += '# %s\n\n' % _("Type >help< followed by Run Code for a list of FlatCAM Tcl Commands "
  2343. "(displayed in Tcl Shell).")
  2344. def initialize(obj, app):
  2345. obj.source_file = deepcopy(new_source_file)
  2346. outname = 'new_script'
  2347. self.new_object('script', outname, initialize, plot=False)
  2348. def new_document_object(self):
  2349. """
  2350. Creates a new, blank Document object.
  2351. :return: None
  2352. """
  2353. self.defaults.report_usage("new_document_object()")
  2354. def initialize(obj, app):
  2355. obj.source_file = ""
  2356. self.new_object('document', 'new_document', initialize, plot=False)
  2357. def on_object_created(self, obj, plot, auto_select):
  2358. """
  2359. Event callback for object creation.
  2360. It will add the new object to the collection. After that it will plot the object in a threaded way
  2361. :param obj: The newly created FlatCAM object.
  2362. :param plot: if the newly create object t obe plotted
  2363. :param auto_select: if the newly created object to be autoselected after creation
  2364. :return: None
  2365. """
  2366. t0 = time.time() # DEBUG
  2367. self.log.debug("on_object_created()")
  2368. # The Collection might change the name if there is a collision
  2369. self.collection.append(obj)
  2370. # after adding the object to the collection always update the list of objects that are in the collection
  2371. self.all_objects_list = self.collection.get_list()
  2372. # self.inform.emit('[selected] %s created & selected: %s' %
  2373. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2374. if obj.kind == 'gerber':
  2375. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2376. kind=obj.kind.capitalize(),
  2377. color='green',
  2378. name=str(obj.options['name']), tx=_("created/selected"))
  2379. )
  2380. elif obj.kind == 'excellon':
  2381. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2382. kind=obj.kind.capitalize(),
  2383. color='brown',
  2384. name=str(obj.options['name']), tx=_("created/selected"))
  2385. )
  2386. elif obj.kind == 'cncjob':
  2387. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2388. kind=obj.kind.capitalize(),
  2389. color='blue',
  2390. name=str(obj.options['name']), tx=_("created/selected"))
  2391. )
  2392. elif obj.kind == 'geometry':
  2393. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2394. kind=obj.kind.capitalize(),
  2395. color='red',
  2396. name=str(obj.options['name']), tx=_("created/selected"))
  2397. )
  2398. elif obj.kind == 'script':
  2399. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2400. kind=obj.kind.capitalize(),
  2401. color='orange',
  2402. name=str(obj.options['name']), tx=_("created/selected"))
  2403. )
  2404. elif obj.kind == 'document':
  2405. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2406. kind=obj.kind.capitalize(),
  2407. color='darkCyan',
  2408. name=str(obj.options['name']), tx=_("created/selected"))
  2409. )
  2410. # update the SHELL auto-completer model with the name of the new object
  2411. self.shell._edit.set_model_data(self.myKeywords)
  2412. if auto_select:
  2413. # select the just opened object but deselect the previous ones
  2414. self.collection.set_all_inactive()
  2415. self.collection.set_active(obj.options["name"])
  2416. else:
  2417. self.collection.set_all_inactive()
  2418. # here it is done the object plotting
  2419. def worker_task(t_obj):
  2420. with self.proc_container.new(_("Plotting")):
  2421. if isinstance(t_obj, CNCJobObject):
  2422. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2423. else:
  2424. t_obj.plot()
  2425. t1 = time.time() # DEBUG
  2426. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2427. self.object_plotted.emit(t_obj)
  2428. # Send to worker
  2429. # self.worker.add_task(worker_task, [self])
  2430. if plot is True:
  2431. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2432. def on_object_changed(self, obj):
  2433. """
  2434. Called whenever the geometry of the object was changed in some way.
  2435. This require the update of it's bounding values so it can be the selected on canvas.
  2436. Update the bounding box data from obj.options
  2437. :param obj: the object that was changed
  2438. :return: None
  2439. """
  2440. try:
  2441. xmin, ymin, xmax, ymax = obj.bounds()
  2442. except TypeError:
  2443. return
  2444. obj.options['xmin'] = xmin
  2445. obj.options['ymin'] = ymin
  2446. obj.options['xmax'] = xmax
  2447. obj.options['ymax'] = ymax
  2448. log.debug("Object changed, updating the bounding box data on self.options")
  2449. # delete the old selection shape
  2450. self.delete_selection_shape()
  2451. self.should_we_save = True
  2452. def on_object_plotted(self):
  2453. """
  2454. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2455. :return: None
  2456. """
  2457. self.on_zoom_fit(None)
  2458. def on_about(self):
  2459. """
  2460. Displays the "about" dialog found in the Menu --> Help.
  2461. :return: None
  2462. """
  2463. self.defaults.report_usage("on_about")
  2464. version = self.version
  2465. version_date = self.version_date
  2466. beta = self.beta
  2467. class AboutDialog(QtWidgets.QDialog):
  2468. def __init__(self, app, parent=None):
  2469. QtWidgets.QDialog.__init__(self, parent)
  2470. self.app = app
  2471. # Icon and title
  2472. self.setWindowIcon(parent.app_icon)
  2473. self.setWindowTitle(_("About FlatCAM"))
  2474. self.resize(600, 200)
  2475. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2476. # self.setStyleSheet(
  2477. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2478. # "background-attachment: fixed"
  2479. # )
  2480. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2481. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2482. # palette = QtGui.QPalette()
  2483. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2484. # self.setPalette(palette)
  2485. logo = QtWidgets.QLabel()
  2486. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2487. title = QtWidgets.QLabel(
  2488. "<font size=8><B>FlatCAM</B></font><BR>"
  2489. "{title}<BR>"
  2490. "<BR>"
  2491. "<BR>"
  2492. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2493. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2494. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2495. "<B>{issue}</B></a><BR>".format(
  2496. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2497. devel=_("Development"),
  2498. down=_("DOWNLOAD"),
  2499. issue=_("Issue tracker"))
  2500. )
  2501. title.setOpenExternalLinks(True)
  2502. closebtn = QtWidgets.QPushButton(_("Close"))
  2503. tab_widget = QtWidgets.QTabWidget()
  2504. description_label = QtWidgets.QLabel(
  2505. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2506. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2507. version=version,
  2508. beta=('BETA' if beta else ''),
  2509. date=version_date,
  2510. arch=platform.architecture()[0])
  2511. )
  2512. description_label.setOpenExternalLinks(True)
  2513. lic_lbl_header = QtWidgets.QLabel(
  2514. '%s:<br>%s<br>' % (
  2515. _('Licensed under the MIT license'),
  2516. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2517. "http://www.opensource.org/licenses/mit-license.php</a>"
  2518. )
  2519. )
  2520. lic_lbl_header.setOpenExternalLinks(True)
  2521. lic_lbl_body = QtWidgets.QLabel(
  2522. _(
  2523. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2524. 'of this software and associated documentation files (the "Software"), to deal\n'
  2525. 'in the Software without restriction, including without limitation the rights\n'
  2526. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2527. 'copies of the Software, and to permit persons to whom the Software is\n'
  2528. 'furnished to do so, subject to the following conditions:\n\n'
  2529. 'The above copyright notice and this permission notice shall be included in\n'
  2530. 'all copies or substantial portions of the Software.\n\n'
  2531. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2532. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2533. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2534. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2535. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2536. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2537. 'THE SOFTWARE.'
  2538. )
  2539. )
  2540. attributions_label = QtWidgets.QLabel(
  2541. _(
  2542. 'Some of the icons used are from the following sources:<br>'
  2543. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2544. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2545. 'title="Flaticon">www.flaticon.com</a></div>'
  2546. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2547. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2548. )
  2549. )
  2550. attributions_label.setOpenExternalLinks(True)
  2551. # layouts
  2552. layout1 = QtWidgets.QVBoxLayout()
  2553. layout1_1 = QtWidgets.QHBoxLayout()
  2554. layout1_2 = QtWidgets.QHBoxLayout()
  2555. layout2 = QtWidgets.QHBoxLayout()
  2556. layout3 = QtWidgets.QHBoxLayout()
  2557. self.setLayout(layout1)
  2558. layout1.addLayout(layout1_1)
  2559. layout1.addLayout(layout1_2)
  2560. layout1.addLayout(layout2)
  2561. layout1.addLayout(layout3)
  2562. layout1_1.addStretch()
  2563. layout1_1.addWidget(description_label)
  2564. layout1_2.addWidget(tab_widget)
  2565. self.splash_tab = QtWidgets.QWidget()
  2566. self.splash_tab.setObjectName("splash_about")
  2567. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2568. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2569. tab_widget.addTab(self.splash_tab, _("Splash"))
  2570. self.programmmers_tab = QtWidgets.QWidget()
  2571. self.programmmers_tab.setObjectName("programmers_about")
  2572. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2573. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2574. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2575. self.translators_tab = QtWidgets.QWidget()
  2576. self.translators_tab.setObjectName("translators_about")
  2577. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2578. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2579. tab_widget.addTab(self.translators_tab, _("Translators"))
  2580. self.license_tab = QtWidgets.QWidget()
  2581. self.license_tab.setObjectName("license_about")
  2582. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2583. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2584. tab_widget.addTab(self.license_tab, _("License"))
  2585. self.attributions_tab = QtWidgets.QWidget()
  2586. self.attributions_tab.setObjectName("attributions_about")
  2587. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2588. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2589. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2590. self.splash_tab_layout.addWidget(logo, stretch=0)
  2591. self.splash_tab_layout.addWidget(title, stretch=1)
  2592. pal = QtGui.QPalette()
  2593. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2594. self.prog_grid_lay = QtWidgets.QGridLayout()
  2595. self.prog_grid_lay.setHorizontalSpacing(20)
  2596. self.prog_grid_lay.setColumnStretch(0, 0)
  2597. self.prog_grid_lay.setColumnStretch(2, 1)
  2598. prog_widget = QtWidgets.QWidget()
  2599. prog_widget.setLayout(self.prog_grid_lay)
  2600. prog_scroll = QtWidgets.QScrollArea()
  2601. prog_scroll.setWidget(prog_widget)
  2602. prog_scroll.setWidgetResizable(True)
  2603. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2604. prog_scroll.setPalette(pal)
  2605. self.programmmers_tab_layout.addWidget(prog_scroll)
  2606. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2607. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2608. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2609. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2610. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2611. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2612. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2613. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2614. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2615. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2616. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2617. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2618. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2619. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2620. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2621. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2622. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2623. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2624. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2625. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2626. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2627. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2628. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2629. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2630. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2631. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2632. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2633. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2634. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2635. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2636. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2637. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2638. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2639. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2640. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2641. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2642. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2643. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2644. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2645. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2646. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2647. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2648. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2649. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2650. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2651. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2652. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2653. self.translator_grid_lay = QtWidgets.QGridLayout()
  2654. self.translator_grid_lay.setColumnStretch(0, 0)
  2655. self.translator_grid_lay.setColumnStretch(1, 0)
  2656. self.translator_grid_lay.setColumnStretch(2, 1)
  2657. self.translator_grid_lay.setColumnStretch(3, 0)
  2658. # trans_widget = QtWidgets.QWidget()
  2659. # trans_widget.setLayout(self.translator_grid_lay)
  2660. # self.translators_tab_layout.addWidget(trans_widget)
  2661. # self.translators_tab_layout.addStretch()
  2662. trans_widget = QtWidgets.QWidget()
  2663. trans_widget.setLayout(self.translator_grid_lay)
  2664. trans_scroll = QtWidgets.QScrollArea()
  2665. trans_scroll.setWidget(trans_widget)
  2666. trans_scroll.setWidgetResizable(True)
  2667. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2668. trans_scroll.setPalette(pal)
  2669. self.translators_tab_layout.addWidget(trans_scroll)
  2670. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2671. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2672. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2673. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2674. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2675. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2676. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2677. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2678. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2679. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2680. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2681. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2682. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2683. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2684. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2685. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2686. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2687. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2688. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2689. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2690. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2691. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2692. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2693. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2694. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2695. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2696. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2697. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2698. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2699. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2700. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2701. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2702. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2703. self.translator_grid_lay.setColumnStretch(0, 0)
  2704. self.translators_tab_layout.addStretch()
  2705. self.license_tab_layout.addWidget(lic_lbl_header)
  2706. self.license_tab_layout.addWidget(lic_lbl_body)
  2707. self.license_tab_layout.addStretch()
  2708. self.attributions_tab_layout.addWidget(attributions_label)
  2709. self.attributions_tab_layout.addStretch()
  2710. layout3.addStretch()
  2711. layout3.addWidget(closebtn)
  2712. closebtn.clicked.connect(self.accept)
  2713. AboutDialog(app=self, parent=self.ui).exec_()
  2714. def install_bookmarks(self, book_dict=None):
  2715. """
  2716. Install the bookmarks actions in the Help menu -> Bookmarks
  2717. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2718. :return: None
  2719. """
  2720. if book_dict is None:
  2721. self.defaults["global_bookmarks"].update(
  2722. {
  2723. '1': ['FlatCAM', "http://flatcam.org"],
  2724. '2': ['Backup Site', ""]
  2725. }
  2726. )
  2727. else:
  2728. self.defaults["global_bookmarks"].clear()
  2729. self.defaults["global_bookmarks"].update(book_dict)
  2730. # first try to disconnect if somehow they get connected from elsewhere
  2731. for act in self.ui.menuhelp_bookmarks.actions():
  2732. try:
  2733. act.triggered.disconnect()
  2734. except TypeError:
  2735. pass
  2736. # clear all actions except the last one who is the Bookmark manager
  2737. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2738. pass
  2739. else:
  2740. self.ui.menuhelp_bookmarks.removeAction(act)
  2741. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2742. if self.defaults["global_bookmarks"]:
  2743. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2744. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2745. # the JSON is first making the keys as strings (therefore I have to use strings too
  2746. # or do the conversion :(
  2747. # )
  2748. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2749. # the '10' entry jsut after '1' therefore ordering as strings
  2750. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2751. key=lambda x: int(x[0]))
  2752. for entry, bookmark in sorted_bookmarks:
  2753. title = bookmark[0]
  2754. weblink = bookmark[1]
  2755. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2756. act.setText(title)
  2757. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2758. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2759. if title == 'Backup Site' and weblink == "":
  2760. act.triggered.connect(self.on_backup_site)
  2761. else:
  2762. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2763. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2764. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2765. def on_bookmarks_manager(self):
  2766. """
  2767. Adds the bookmark manager in a Tab in Plot Area
  2768. :return:
  2769. """
  2770. for idx in range(self.ui.plot_tab_area.count()):
  2771. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2772. # there can be only one instance of Bookmark Manager at one time
  2773. return
  2774. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2775. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2776. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2777. # add the tab if it was closed
  2778. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2779. # delete the absolute and relative position and messages in the infobar
  2780. self.ui.position_label.setText("")
  2781. # self.ui.rel_position_label.setText("")
  2782. # Switch plot_area to preferences page
  2783. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2784. def on_backup_site(self):
  2785. msgbox = QtWidgets.QMessageBox()
  2786. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2787. "1. FlatCAM.org website is down\n"
  2788. "2. Someone forked FlatCAM project and wants to point\n"
  2789. "to his own website\n\n"
  2790. "If you can't get any informations about FlatCAM beta\n"
  2791. "use the YouTube channel link from the Help menu."))
  2792. msgbox.setWindowTitle(_("Alternative website"))
  2793. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2794. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2795. msgbox.setDefaultButton(bt_yes)
  2796. msgbox.exec_()
  2797. # response = msgbox.clickedButton()
  2798. def on_file_savedefaults(self):
  2799. """
  2800. Callback for menu item File->Save Defaults. Saves application default options
  2801. ``self.defaults`` to current_defaults.FlatConfig.
  2802. :return: None
  2803. """
  2804. self.preferencesUiManager.save_defaults()
  2805. def final_save(self):
  2806. """
  2807. Callback for doing a preferences save to file whenever the application is about to quit.
  2808. If the project has changes, it will ask the user to save the project.
  2809. :return: None
  2810. """
  2811. if self.save_in_progress:
  2812. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2813. return
  2814. if self.should_we_save and self.collection.get_list():
  2815. msgbox = QtWidgets.QMessageBox()
  2816. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2817. "\n"
  2818. "Do you want to Save the project?"))
  2819. msgbox.setWindowTitle(_("Save changes"))
  2820. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2821. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2822. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2823. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2824. msgbox.setDefaultButton(bt_yes)
  2825. msgbox.exec_()
  2826. response = msgbox.clickedButton()
  2827. if response == bt_yes:
  2828. try:
  2829. self.trayIcon.hide()
  2830. except Exception:
  2831. pass
  2832. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2833. elif response == bt_no:
  2834. try:
  2835. self.trayIcon.hide()
  2836. except Exception:
  2837. pass
  2838. self.quit_application()
  2839. elif response == bt_cancel:
  2840. return
  2841. else:
  2842. try:
  2843. self.trayIcon.hide()
  2844. except Exception:
  2845. pass
  2846. self.quit_application()
  2847. def quit_application(self):
  2848. """
  2849. Called (as a pyslot or not) when the application is quit.
  2850. :return: None
  2851. """
  2852. self.preferencesUiManager.save_defaults(silent=True)
  2853. log.debug("App.quit_application() --> App Defaults saved.")
  2854. if self.cmd_line_headless != 1:
  2855. # save app state to file
  2856. stgs = QSettings("Open Source", "FlatCAM")
  2857. stgs.setValue('saved_gui_state', self.ui.saveState())
  2858. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2859. stgs.setValue(
  2860. 'language',
  2861. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2862. )
  2863. stgs.setValue(
  2864. 'notebook_font_size',
  2865. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2866. )
  2867. stgs.setValue(
  2868. 'axis_font_size',
  2869. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2870. )
  2871. stgs.setValue(
  2872. 'textbox_font_size',
  2873. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2874. )
  2875. stgs.setValue(
  2876. 'hud_font_size',
  2877. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2878. )
  2879. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2880. stgs.setValue(
  2881. 'machinist',
  2882. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2883. )
  2884. # This will write the setting to the platform specific storage.
  2885. del stgs
  2886. log.debug("App.quit_application() --> App UI state saved.")
  2887. # try to quit the Socket opened by ArgsThread class
  2888. try:
  2889. self.new_launch.stop.emit()
  2890. except Exception as err:
  2891. log.debug("App.quit_application() --> %s" % str(err))
  2892. # try to quit the QThread that run ArgsThread class
  2893. try:
  2894. self.th.quit()
  2895. except Exception as e:
  2896. log.debug("App.quit_application() --> %s" % str(e))
  2897. # terminate workers
  2898. self.workers.__del__()
  2899. # quit app by signalling for self.kill_app() method
  2900. # self.close_app_signal.emit()
  2901. QtWidgets.qApp.quit()
  2902. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2903. # we use the following command
  2904. minor_v = sys.version_info.minor
  2905. if minor_v < 8:
  2906. sys.exit(0)
  2907. else:
  2908. os._exit(0) # fix to work with Python 3.8
  2909. @staticmethod
  2910. def kill_app():
  2911. QtWidgets.qApp.quit()
  2912. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2913. # we use the following command
  2914. sys.exit(0)
  2915. def on_portable_checked(self, state):
  2916. """
  2917. Callback called when the checkbox in Preferences AppGUI is checked.
  2918. It will set the application as portable by creating the preferences and recent files in the
  2919. 'config' folder found in the FlatCAM installation folder.
  2920. :param state: boolean, the state of the checkbox when clicked/checked
  2921. :return:
  2922. """
  2923. line_no = 0
  2924. data = None
  2925. if sys.platform != 'win32':
  2926. # this won't work in Linux or MacOS
  2927. return
  2928. # test if the app was frozen and choose the path for the configuration file
  2929. if getattr(sys, "frozen", False) is True:
  2930. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2931. else:
  2932. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2933. config_file = current_data_path + '\\configuration.txt'
  2934. try:
  2935. with open(config_file, 'r') as f:
  2936. try:
  2937. data = f.readlines()
  2938. except Exception as e:
  2939. log.debug('App.__init__() -->%s' % str(e))
  2940. return
  2941. except FileNotFoundError:
  2942. pass
  2943. for line in data:
  2944. line = line.strip('\n')
  2945. param = str(line).rpartition('=')
  2946. if param[0] == 'portable':
  2947. break
  2948. line_no += 1
  2949. if state:
  2950. data[line_no] = 'portable=True\n'
  2951. # create the new defauults files
  2952. # create current_defaults.FlatConfig file if there is none
  2953. try:
  2954. f = open(current_data_path + '/current_defaults.FlatConfig')
  2955. f.close()
  2956. except IOError:
  2957. App.log.debug('Creating empty current_defaults.FlatConfig')
  2958. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2959. json.dump({}, f)
  2960. f.close()
  2961. # create factory_defaults.FlatConfig file if there is none
  2962. try:
  2963. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2964. f.close()
  2965. except IOError:
  2966. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2967. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2968. json.dump({}, f)
  2969. f.close()
  2970. try:
  2971. f = open(current_data_path + '/recent.json')
  2972. f.close()
  2973. except IOError:
  2974. App.log.debug('Creating empty recent.json')
  2975. f = open(current_data_path + '/recent.json', 'w')
  2976. json.dump([], f)
  2977. f.close()
  2978. try:
  2979. fp = open(current_data_path + '/recent_projects.json')
  2980. fp.close()
  2981. except IOError:
  2982. App.log.debug('Creating empty recent_projects.json')
  2983. fp = open(current_data_path + '/recent_projects.json', 'w')
  2984. json.dump([], fp)
  2985. fp.close()
  2986. # save the current defaults to the new defaults file
  2987. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2988. else:
  2989. data[line_no] = 'portable=False\n'
  2990. with open(config_file, 'w') as f:
  2991. f.writelines(data)
  2992. def on_register_files(self, obj_type=None):
  2993. """
  2994. Called whenever there is a need to register file extensions with FlatCAM.
  2995. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2996. :param obj_type: the type of object to be register for.
  2997. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2998. :return: None
  2999. """
  3000. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3001. new_reg_path = 'Software\\Classes\\'
  3002. # find if the current user is admin
  3003. try:
  3004. is_admin = os.getuid() == 0
  3005. except AttributeError:
  3006. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3007. if is_admin is True:
  3008. root_path = winreg.HKEY_LOCAL_MACHINE
  3009. else:
  3010. root_path = winreg.HKEY_CURRENT_USER
  3011. # create the keys
  3012. def set_reg(name, root_pth, new_reg_path, value):
  3013. try:
  3014. winreg.CreateKey(root_pth, new_reg_path)
  3015. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3016. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3017. return True
  3018. except WindowsError:
  3019. return False
  3020. # delete key in registry
  3021. def delete_reg(root_pth, reg_path, key_to_del):
  3022. key_to_del_path = reg_path + key_to_del
  3023. try:
  3024. winreg.DeleteKey(root_pth, key_to_del_path)
  3025. return True
  3026. except WindowsError:
  3027. return False
  3028. if obj_type is None or obj_type == 'excellon':
  3029. exc_list = \
  3030. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3031. exc_list = [x for x in exc_list if x != '']
  3032. # register all keys in the Preferences window
  3033. for ext in exc_list:
  3034. new_k = new_reg_path + '.%s' % ext
  3035. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3036. # and unregister those that are no longer in the Preferences windows but are in the file
  3037. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3038. if ext not in exc_list:
  3039. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3040. # now write the updated extensions to the self.defaults
  3041. # new_ext = ''
  3042. # for ext in exc_list:
  3043. # new_ext = new_ext + ext + ', '
  3044. # self.defaults["fa_excellon"] = new_ext
  3045. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3046. if obj_type is None or obj_type == 'gcode':
  3047. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3048. gco_list = [x for x in gco_list if x != '']
  3049. # register all keys in the Preferences window
  3050. for ext in gco_list:
  3051. new_k = new_reg_path + '.%s' % ext
  3052. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3053. # and unregister those that are no longer in the Preferences windows but are in the file
  3054. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3055. if ext not in gco_list:
  3056. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3057. # now write the updated extensions to the self.defaults
  3058. # new_ext = ''
  3059. # for ext in gco_list:
  3060. # new_ext = new_ext + ext + ', '
  3061. # self.defaults["fa_gcode"] = new_ext
  3062. self.inform.emit('[success] %s' %
  3063. _("Selected GCode file extensions registered with FlatCAM."))
  3064. if obj_type is None or obj_type == 'gerber':
  3065. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3066. grb_list = [x for x in grb_list if x != '']
  3067. # register all keys in the Preferences window
  3068. for ext in grb_list:
  3069. new_k = new_reg_path + '.%s' % ext
  3070. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3071. # and unregister those that are no longer in the Preferences windows but are in the file
  3072. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3073. if ext not in grb_list:
  3074. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3075. # now write the updated extensions to the self.defaults
  3076. # new_ext = ''
  3077. # for ext in grb_list:
  3078. # new_ext = new_ext + ext + ', '
  3079. # self.defaults["fa_gerber"] = new_ext
  3080. self.inform.emit('[success] %s' %
  3081. _("Selected Gerber file extensions registered with FlatCAM."))
  3082. def add_extension(self, ext_type):
  3083. """
  3084. Add a file extension to the list for a specific object
  3085. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3086. :return:
  3087. """
  3088. if ext_type == 'excellon':
  3089. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3090. if new_ext == '':
  3091. return
  3092. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3093. if new_ext in old_val:
  3094. return
  3095. old_val.append(new_ext)
  3096. old_val.sort()
  3097. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3098. if ext_type == 'gcode':
  3099. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3100. if new_ext == '':
  3101. return
  3102. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3103. if new_ext in old_val:
  3104. return
  3105. old_val.append(new_ext)
  3106. old_val.sort()
  3107. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3108. if ext_type == 'gerber':
  3109. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3110. if new_ext == '':
  3111. return
  3112. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3113. if new_ext in old_val:
  3114. return
  3115. old_val.append(new_ext)
  3116. old_val.sort()
  3117. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3118. if ext_type == 'keyword':
  3119. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3120. if new_kw == '':
  3121. return
  3122. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3123. if new_kw in old_val:
  3124. return
  3125. old_val.append(new_kw)
  3126. old_val.sort()
  3127. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3128. # update the self.myKeywords so the model is updated
  3129. self.autocomplete_kw_list = \
  3130. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3131. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3132. self.shell._edit.set_model_data(self.myKeywords)
  3133. def del_extension(self, ext_type):
  3134. """
  3135. Remove a file extension from the list for a specific object
  3136. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3137. :return:
  3138. """
  3139. if ext_type == 'excellon':
  3140. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3141. if new_ext == '':
  3142. return
  3143. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3144. if new_ext not in old_val:
  3145. return
  3146. old_val.remove(new_ext)
  3147. old_val.sort()
  3148. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3149. if ext_type == 'gcode':
  3150. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3151. if new_ext == '':
  3152. return
  3153. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3154. if new_ext not in old_val:
  3155. return
  3156. old_val.remove(new_ext)
  3157. old_val.sort()
  3158. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3159. if ext_type == 'gerber':
  3160. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3161. if new_ext == '':
  3162. return
  3163. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3164. if new_ext not in old_val:
  3165. return
  3166. old_val.remove(new_ext)
  3167. old_val.sort()
  3168. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3169. if ext_type == 'keyword':
  3170. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3171. if new_kw == '':
  3172. return
  3173. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3174. if new_kw not in old_val:
  3175. return
  3176. old_val.remove(new_kw)
  3177. old_val.sort()
  3178. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3179. # update the self.myKeywords so the model is updated
  3180. self.autocomplete_kw_list = \
  3181. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3182. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3183. self.shell._edit.set_model_data(self.myKeywords)
  3184. def restore_extensions(self, ext_type):
  3185. """
  3186. Restore all file extensions associations with FlatCAM, for a specific object
  3187. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3188. :return:
  3189. """
  3190. if ext_type == 'excellon':
  3191. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3192. # for the ability to open Excellon files with .txt extension
  3193. new_exc_list = deepcopy(self.exc_list)
  3194. try:
  3195. new_exc_list.remove('txt')
  3196. except ValueError:
  3197. pass
  3198. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3199. if ext_type == 'gcode':
  3200. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3201. if ext_type == 'gerber':
  3202. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3203. if ext_type == 'keyword':
  3204. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3205. # update the self.myKeywords so the model is updated
  3206. self.autocomplete_kw_list = self.default_keywords
  3207. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3208. self.shell._edit.set_model_data(self.myKeywords)
  3209. def delete_all_extensions(self, ext_type):
  3210. """
  3211. Delete all file extensions associations with FlatCAM, for a specific object
  3212. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3213. :return:
  3214. """
  3215. if ext_type == 'excellon':
  3216. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3217. if ext_type == 'gcode':
  3218. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3219. if ext_type == 'gerber':
  3220. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3221. if ext_type == 'keyword':
  3222. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3223. # update the self.myKeywords so the model is updated
  3224. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3225. self.shell._edit.set_model_data(self.myKeywords)
  3226. def on_edit_join(self, name=None):
  3227. """
  3228. Callback for Edit->Join. Joins the selected geometry objects into
  3229. a new one.
  3230. :return: None
  3231. """
  3232. self.defaults.report_usage("on_edit_join()")
  3233. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3234. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3235. geo_type_set = set()
  3236. objs = self.collection.get_selected()
  3237. if len(objs) < 2:
  3238. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3239. (_("At least two objects are required for join. AppObjects currently selected"), len(objs)))
  3240. return 'fail'
  3241. for obj in objs:
  3242. geo_type_set.add(obj.multigeo)
  3243. # if len(geo_type_list) == 1 means that all list elements are the same
  3244. if len(geo_type_set) != 1:
  3245. self.inform.emit('[ERROR] %s' %
  3246. _("Failed join. The Geometry objects are of different types.\n"
  3247. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3248. "convert from one to another and retry joining \n"
  3249. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3250. "the result may not be what was expected. \n"
  3251. "Check the generated GCODE."))
  3252. return
  3253. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3254. if True in geo_type_set:
  3255. def initialize(geo_obj, app):
  3256. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  3257. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3258. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3259. for v in geo_obj.tools.values():
  3260. v['data']['name'] = obj_name_multi
  3261. self.new_object("geometry", obj_name_multi, initialize)
  3262. else:
  3263. def initialize(geo_obj, app):
  3264. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  3265. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3266. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3267. for v in geo_obj.tools.values():
  3268. v['data']['name'] = obj_name_single
  3269. self.new_object("geometry", obj_name_single, initialize)
  3270. self.should_we_save = True
  3271. def on_edit_join_exc(self):
  3272. """
  3273. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3274. a new Excellon.
  3275. :return: None
  3276. """
  3277. self.defaults.report_usage("on_edit_join_exc()")
  3278. objs = self.collection.get_selected()
  3279. for obj in objs:
  3280. if not isinstance(obj, ExcellonObject):
  3281. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3282. return
  3283. if len(objs) < 2:
  3284. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3285. (_("At least two objects are required for join. AppObjects currently selected"), len(objs)))
  3286. return 'fail'
  3287. def initialize(exc_obj, app):
  3288. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3289. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3290. self.new_object("excellon", 'Combo_Excellon', initialize)
  3291. self.should_we_save = True
  3292. def on_edit_join_grb(self):
  3293. """
  3294. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3295. a new Gerber object.
  3296. :return: None
  3297. """
  3298. self.defaults.report_usage("on_edit_join_grb()")
  3299. objs = self.collection.get_selected()
  3300. for obj in objs:
  3301. if not isinstance(obj, GerberObject):
  3302. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3303. return
  3304. if len(objs) < 2:
  3305. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3306. (_("At least two objects are required for join. AppObjects currently selected"), len(objs)))
  3307. return 'fail'
  3308. def initialize(grb_obj, app):
  3309. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3310. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3311. self.new_object("gerber", 'Combo_Gerber', initialize)
  3312. self.should_we_save = True
  3313. def on_convert_singlegeo_to_multigeo(self):
  3314. """
  3315. Called for converting a Geometry object from single-geo to multi-geo.
  3316. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3317. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3318. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3319. the solid-geometry of that tool.
  3320. :return: None
  3321. """
  3322. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3323. obj = self.collection.get_active()
  3324. if obj is None:
  3325. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3326. return
  3327. if not isinstance(obj, GeometryObject):
  3328. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3329. return
  3330. obj.multigeo = True
  3331. for tooluid, dict_value in obj.tools.items():
  3332. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3333. if not isinstance(obj.solid_geometry, list):
  3334. obj.solid_geometry = [obj.solid_geometry]
  3335. # obj.solid_geometry[:] = []
  3336. obj.plot()
  3337. self.should_we_save = True
  3338. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3339. def on_convert_multigeo_to_singlegeo(self):
  3340. """
  3341. Called for converting a Geometry object from multi-geo to single-geo.
  3342. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3343. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3344. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3345. the solid-geometry of that tool.
  3346. :return: None
  3347. """
  3348. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3349. obj = self.collection.get_active()
  3350. if obj is None:
  3351. self.inform.emit('[ERROR_NOTCL] %s' %
  3352. _("Failed. Select a Geometry Object and try again."))
  3353. return
  3354. if not isinstance(obj, GeometryObject):
  3355. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3356. (_("Expected a GeometryObject, got"), type(obj)))
  3357. return
  3358. obj.multigeo = False
  3359. total_solid_geometry = []
  3360. for tooluid, dict_value in obj.tools.items():
  3361. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3362. # clear the original geometry
  3363. dict_value['solid_geometry'][:] = []
  3364. obj.solid_geometry = deepcopy(total_solid_geometry)
  3365. obj.plot()
  3366. self.should_we_save = True
  3367. self.inform.emit('[success] %s' %
  3368. _("A Geometry object was converted to SingleGeo type."))
  3369. def on_defaults_dict_change(self, field):
  3370. """
  3371. Called whenever a key changed in the self.defaults dictionary. It will set the required AppGUI element in the
  3372. Edit -> Preferences tab window.
  3373. :param field: the key of the self.defaults dictionary that was changed.
  3374. :return: None
  3375. """
  3376. self.preferencesUiManager.defaults_write_form_field(field=field)
  3377. if field == "units":
  3378. self.set_screen_units(self.defaults['units'])
  3379. def set_screen_units(self, units):
  3380. """
  3381. Set the FlatCAM units on the status bar.
  3382. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3383. :return: None
  3384. """
  3385. self.ui.units_label.setText("[" + units.lower() + "]")
  3386. def on_toggle_units_click(self):
  3387. try:
  3388. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3389. except (TypeError, AttributeError):
  3390. pass
  3391. if self.defaults["units"] == 'MM':
  3392. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3393. else:
  3394. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3395. self.on_toggle_units(no_pref=True)
  3396. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3397. lambda: self.on_toggle_units(no_pref=False))
  3398. def on_toggle_units(self, no_pref=False):
  3399. """
  3400. Callback for the Units radio-button change in the Preferences tab.
  3401. Changes the application's default units adn for the project too.
  3402. If changing the project's units, the change propagates to all of
  3403. the objects in the project.
  3404. :return: None
  3405. """
  3406. self.defaults.report_usage("on_toggle_units")
  3407. if self.toggle_units_ignore:
  3408. return
  3409. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3410. # If option is the same, then ignore
  3411. if new_units == self.defaults["units"].upper():
  3412. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3413. return
  3414. # Keys in self.defaults for which to scale their values
  3415. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3416. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3417. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3418. "gerber_editor_ma_high",
  3419. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3420. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3421. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3422. "excellon_feedrate_probe", "excellon_milling_dia",
  3423. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3424. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3425. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3426. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3427. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3428. "geometry_extracut_length", "geometry_z_pdepth",
  3429. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3430. 'cncjob_tooldia',
  3431. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3432. "tools_paintnewdia",
  3433. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3434. "tools_nccnewdia", "tools_ncc_offset_value",
  3435. "tools_2sided_drilldia",
  3436. "tools_film_boundary", "tools_film_scale_stroke",
  3437. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3438. "tools_cutout_depthperpass",
  3439. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3440. "tools_panelize_spacing_rows",
  3441. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3442. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3443. "tools_transform_buffer_dis",
  3444. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3445. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3446. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3447. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3448. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3449. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3450. "tools_cr_h2h_val", "tools_cr_dh_val",
  3451. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3452. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3453. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3454. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3455. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3456. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3457. "tools_copper_thieving_mask_clearance",
  3458. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3459. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3460. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3461. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3462. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3463. "tools_invert_margin",
  3464. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3465. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3466. def scale_defaults(sfactor):
  3467. for dim in dimensions:
  3468. if dim in [
  3469. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3470. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3471. 'tools_transform_mirror_point'
  3472. ]:
  3473. if self.defaults[dim] is None or self.defaults[dim] == '':
  3474. continue
  3475. try:
  3476. coordinates = self.defaults[dim].split(",")
  3477. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3478. coords_xy[0] *= sfactor
  3479. coords_xy[1] *= sfactor
  3480. self.defaults[dim] = "%.*f, %.*f" % (
  3481. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3482. except Exception as e:
  3483. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3484. elif dim in [
  3485. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3486. ]:
  3487. if self.defaults[dim] is None or self.defaults[dim] == '':
  3488. continue
  3489. try:
  3490. self.defaults[dim] = float(self.defaults[dim])
  3491. tools_diameters = [self.defaults[dim]]
  3492. except ValueError:
  3493. try:
  3494. tools_string = self.defaults[dim].split(",")
  3495. tools_diameters = [eval(a) for a in tools_string if a != '']
  3496. except Exception as e:
  3497. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3498. continue
  3499. self.defaults[dim] = ''
  3500. td_len = len(tools_diameters)
  3501. if td_len > 1:
  3502. for t in range(td_len):
  3503. tools_diameters[t] *= sfactor
  3504. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3505. else:
  3506. tools_diameters[0] *= sfactor
  3507. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3508. elif dim in ['global_gridx', 'global_gridy']:
  3509. # format the number of decimals to the one specified in self.decimals
  3510. try:
  3511. val = float(self.defaults[dim]) * sfactor
  3512. except Exception as e:
  3513. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3514. continue
  3515. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3516. else:
  3517. # the number of decimals for the rest is kept unchanged
  3518. if self.defaults[dim]:
  3519. try:
  3520. val = float(self.defaults[dim]) * sfactor
  3521. except Exception as e:
  3522. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3523. continue
  3524. self.defaults[dim] = val
  3525. # The scaling factor depending on choice of units.
  3526. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3527. # Changing project units. Warn user.
  3528. msgbox = QtWidgets.QMessageBox()
  3529. msgbox.setWindowTitle(_("Toggle Units"))
  3530. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3531. msgbox.setText(_("Changing the units of the project\n"
  3532. "will scale all objects.\n\n"
  3533. "Do you want to continue?"))
  3534. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3535. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3536. msgbox.setDefaultButton(bt_ok)
  3537. msgbox.exec_()
  3538. response = msgbox.clickedButton()
  3539. if response == bt_ok:
  3540. if no_pref is False:
  3541. self.preferencesUiManager.defaults_read_form()
  3542. scale_defaults(factor)
  3543. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3544. self.defaults["units"] = new_units
  3545. # update the defaults from form, some may assume that the conversion is enough and it's not
  3546. self.on_options_app2project()
  3547. # update the objects
  3548. for obj in self.collection.get_list():
  3549. obj.convert_units(new_units)
  3550. # make that the properties stored in the object are also updated
  3551. self.object_changed.emit(obj)
  3552. # rebuild the object UI
  3553. obj.build_ui()
  3554. # change this only if the workspace is active
  3555. if self.defaults['global_workspace'] is True:
  3556. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3557. # adjust the grid values on the main toolbar
  3558. val_x = float(self.defaults['global_gridx']) * factor
  3559. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3560. current = self.collection.get_active()
  3561. if current is not None:
  3562. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3563. if not isinstance(current, GeometryObject):
  3564. current.to_form()
  3565. # replot all objects
  3566. self.plot_all()
  3567. # set the status labels to reflect the current FlatCAM units
  3568. self.set_screen_units(new_units)
  3569. # signal to the app that we changed the object properties and it should save the project
  3570. self.should_we_save = True
  3571. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3572. else:
  3573. # Undo toggling
  3574. self.toggle_units_ignore = True
  3575. if self.defaults['units'].upper() == 'MM':
  3576. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3577. else:
  3578. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3579. self.toggle_units_ignore = False
  3580. # store the grid values so they are not changed in the next step
  3581. val_x = float(self.defaults['global_gridx'])
  3582. val_y = float(self.defaults['global_gridy'])
  3583. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3584. self.preferencesUiManager.defaults_read_form()
  3585. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3586. # in self.defaults from the AppGUI elements but
  3587. # I don't want it for the grid values, so I update them here
  3588. self.defaults['global_gridx'] = val_x
  3589. self.defaults['global_gridy'] = val_y
  3590. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3591. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3592. def on_toggle_axis(self):
  3593. self.defaults.report_usage("on_toggle_axis()")
  3594. if self.toggle_axis is False:
  3595. if self.is_legacy is False:
  3596. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3597. parent=self.plotcanvas.view.scene)
  3598. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3599. parent=self.plotcanvas.view.scene)
  3600. else:
  3601. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3602. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3603. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3604. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3605. self.plotcanvas.canvas.draw()
  3606. self.toggle_axis = True
  3607. else:
  3608. if self.is_legacy is False:
  3609. self.plotcanvas.v_line.parent = None
  3610. self.plotcanvas.h_line.parent = None
  3611. else:
  3612. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3613. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3614. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3615. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3616. self.plotcanvas.canvas.draw()
  3617. self.toggle_axis = False
  3618. def on_toggle_hud(self):
  3619. self.plotcanvas.on_toggle_hud(state=False if self.plotcanvas.hud_enabled else True)
  3620. def on_toggle_grid_lines(self):
  3621. self.defaults.report_usage("on_toggle_grd_lines()")
  3622. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3623. if tt_settings.contains("theme"):
  3624. theme = tt_settings.value('theme', type=str)
  3625. else:
  3626. theme = 'white'
  3627. if self.toggle_grid_lines is False:
  3628. if self.is_legacy is False:
  3629. if theme == 'white':
  3630. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3631. else:
  3632. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3633. else:
  3634. self.plotcanvas.axes.grid(True)
  3635. try:
  3636. self.plotcanvas.canvas.draw()
  3637. except IndexError:
  3638. pass
  3639. pass
  3640. self.toggle_grid_lines = True
  3641. else:
  3642. if self.is_legacy is False:
  3643. if theme == 'white':
  3644. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3645. else:
  3646. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3647. else:
  3648. self.plotcanvas.axes.grid(False)
  3649. try:
  3650. self.plotcanvas.canvas.draw()
  3651. except IndexError:
  3652. pass
  3653. self.toggle_grid_lines = False
  3654. if self.is_legacy is False:
  3655. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3656. # - perhaps is a bug in VisPy implementation
  3657. if self.grid_status():
  3658. self.app_cursor.enabled = False
  3659. self.app_cursor.enabled = True
  3660. else:
  3661. self.app_cursor.enabled = True
  3662. self.app_cursor.enabled = False
  3663. def on_update_exc_export(self, state):
  3664. """
  3665. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3666. if the update_excellon_cb checkbox is checked
  3667. :param state: state of the checkbox whose signals is tied to his slot
  3668. :return:
  3669. """
  3670. if state:
  3671. # first try to disconnect
  3672. try:
  3673. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3674. disconnect(self.on_excellon_format_changed)
  3675. except TypeError:
  3676. pass
  3677. try:
  3678. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3679. disconnect(self.on_excellon_format_changed)
  3680. except TypeError:
  3681. pass
  3682. try:
  3683. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3684. disconnect(self.on_excellon_format_changed)
  3685. except TypeError:
  3686. pass
  3687. try:
  3688. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3689. disconnect(self.on_excellon_format_changed)
  3690. except TypeError:
  3691. pass
  3692. try:
  3693. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3694. disconnect(self.on_excellon_zeros_changed)
  3695. except TypeError:
  3696. pass
  3697. try:
  3698. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3699. disconnect(self.on_excellon_zeros_changed)
  3700. except TypeError:
  3701. pass
  3702. # the connect them
  3703. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3704. self.on_excellon_format_changed)
  3705. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3706. self.on_excellon_format_changed)
  3707. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3708. self.on_excellon_format_changed)
  3709. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3710. self.on_excellon_format_changed)
  3711. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3712. self.on_excellon_zeros_changed)
  3713. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3714. self.on_excellon_units_changed)
  3715. else:
  3716. # disconnect the signals
  3717. try:
  3718. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3719. disconnect(self.on_excellon_format_changed)
  3720. except TypeError:
  3721. pass
  3722. try:
  3723. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3724. disconnect(self.on_excellon_format_changed)
  3725. except TypeError:
  3726. pass
  3727. try:
  3728. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3729. disconnect(self.on_excellon_format_changed)
  3730. except TypeError:
  3731. pass
  3732. try:
  3733. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3734. disconnect(self.on_excellon_format_changed)
  3735. except TypeError:
  3736. pass
  3737. try:
  3738. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3739. disconnect(self.on_excellon_zeros_changed)
  3740. except TypeError:
  3741. pass
  3742. try:
  3743. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3744. disconnect(self.on_excellon_zeros_changed)
  3745. except TypeError:
  3746. pass
  3747. def on_excellon_format_changed(self):
  3748. """
  3749. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3750. :return: None
  3751. """
  3752. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3753. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3754. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3755. )
  3756. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3757. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3758. )
  3759. else:
  3760. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3761. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3762. )
  3763. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3764. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3765. )
  3766. def on_excellon_zeros_changed(self):
  3767. """
  3768. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3769. :return: None
  3770. """
  3771. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3772. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3773. )
  3774. def on_excellon_units_changed(self):
  3775. """
  3776. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3777. :return: None
  3778. """
  3779. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3780. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3781. )
  3782. self.on_excellon_format_changed()
  3783. def on_film_color_entry(self):
  3784. self.defaults['tools_film_color'] = \
  3785. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3786. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3787. "background-color:%s;"
  3788. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3789. )
  3790. def on_film_color_button(self):
  3791. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3792. c_dialog = QtWidgets.QColorDialog()
  3793. film_color = c_dialog.getColor(initial=current_color)
  3794. if film_color.isValid() is False:
  3795. return
  3796. # if new color is different then mark that the Preferences are changed
  3797. if film_color != current_color:
  3798. self.preferencesUiManager.on_preferences_edited()
  3799. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3800. "background-color:%s;"
  3801. "border-color: dimgray" % str(film_color.name())
  3802. )
  3803. new_val_sel = str(film_color.name())
  3804. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3805. self.defaults['tools_film_color'] = new_val_sel
  3806. def on_qrcode_fill_color_entry(self):
  3807. self.defaults['tools_qrcode_fill_color'] = \
  3808. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3809. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3810. "background-color:%s;"
  3811. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3812. )
  3813. def on_qrcode_fill_color_button(self):
  3814. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3815. c_dialog = QtWidgets.QColorDialog()
  3816. fill_color = c_dialog.getColor(initial=current_color)
  3817. if fill_color.isValid() is False:
  3818. return
  3819. # if new color is different then mark that the Preferences are changed
  3820. if fill_color != current_color:
  3821. self.preferencesUiManager.on_preferences_edited()
  3822. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3823. "background-color:%s;"
  3824. "border-color: dimgray" % str(fill_color.name())
  3825. )
  3826. new_val_sel = str(fill_color.name())
  3827. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3828. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3829. def on_qrcode_back_color_entry(self):
  3830. self.defaults['tools_qrcode_back_color'] = \
  3831. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3832. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3833. "background-color:%s;"
  3834. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3835. )
  3836. def on_qrcode_back_color_button(self):
  3837. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  3838. c_dialog = QtWidgets.QColorDialog()
  3839. back_color = c_dialog.getColor(initial=current_color)
  3840. if back_color.isValid() is False:
  3841. return
  3842. # if new color is different then mark that the Preferences are changed
  3843. if back_color != current_color:
  3844. self.preferencesUiManager.on_preferences_edited()
  3845. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3846. "background-color:%s;"
  3847. "border-color: dimgray" % str(back_color.name())
  3848. )
  3849. new_val_sel = str(back_color.name())
  3850. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  3851. self.defaults['tools_qrcode_back_color'] = new_val_sel
  3852. def on_tab_rmb_click(self, checked):
  3853. self.ui.notebook.set_detachable(val=checked)
  3854. self.defaults["global_tabs_detachable"] = checked
  3855. self.ui.plot_tab_area.set_detachable(val=checked)
  3856. self.defaults["global_tabs_detachable"] = checked
  3857. def on_tab_setup_context_menu(self):
  3858. initial_checked = self.defaults["global_tabs_detachable"]
  3859. action_name = str(_("Detachable Tabs"))
  3860. action = QtWidgets.QAction(self)
  3861. action.setCheckable(True)
  3862. action.setText(action_name)
  3863. action.setChecked(initial_checked)
  3864. self.ui.notebook.tabBar.addAction(action)
  3865. self.ui.plot_tab_area.tabBar.addAction(action)
  3866. try:
  3867. action.triggered.disconnect()
  3868. except TypeError:
  3869. pass
  3870. action.triggered.connect(self.on_tab_rmb_click)
  3871. def on_deselect_all(self):
  3872. self.collection.set_all_inactive()
  3873. self.delete_selection_shape()
  3874. def on_workspace_modified(self):
  3875. # self.save_defaults(silent=True)
  3876. self.plotcanvas.delete_workspace()
  3877. self.preferencesUiManager.defaults_read_form()
  3878. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3879. def on_workspace(self):
  3880. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3881. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3882. self.inform.emit(_("Workspace enabled."))
  3883. else:
  3884. self.plotcanvas.delete_workspace()
  3885. self.inform.emit(_("Workspace disabled."))
  3886. self.preferencesUiManager.defaults_read_form()
  3887. # self.save_defaults(silent=True)
  3888. def on_workspace_toggle(self):
  3889. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3890. try:
  3891. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3892. except TypeError:
  3893. pass
  3894. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3895. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3896. self.on_workspace()
  3897. def on_cursor_type(self, val):
  3898. """
  3899. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3900. :return: None
  3901. """
  3902. self.app_cursor.enabled = False
  3903. if val == 'small':
  3904. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3905. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3906. self.app_cursor = self.plotcanvas.new_cursor()
  3907. else:
  3908. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3909. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3910. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3911. if self.ui.grid_snap_btn.isChecked():
  3912. self.app_cursor.enabled = True
  3913. else:
  3914. self.app_cursor.enabled = False
  3915. def on_tool_add_keypress(self):
  3916. # ## Current application units in Upper Case
  3917. self.units = self.defaults['units'].upper()
  3918. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3919. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3920. if notebook_widget_name == 'selected_tab':
  3921. if self.collection.get_active().kind == 'geometry':
  3922. # Tool add works for Geometry only if Advanced is True in Preferences
  3923. if self.defaults["global_app_level"] == 'a':
  3924. tool_add_popup = FCInputDialog(title="New Tool ...",
  3925. text='Enter a Tool Diameter:',
  3926. min=0.0000, max=99.9999, decimals=4)
  3927. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3928. val, ok = tool_add_popup.get_value()
  3929. if ok:
  3930. if float(val) == 0:
  3931. self.inform.emit('[WARNING_NOTCL] %s' %
  3932. _("Please enter a tool diameter with non-zero value, in Float format."))
  3933. return
  3934. self.collection.get_active().on_tool_add(dia=float(val))
  3935. else:
  3936. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3937. else:
  3938. msgbox = QtWidgets.QMessageBox()
  3939. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3940. "Go to Preferences -> General - Show Advanced Options."))
  3941. msgbox.setWindowTitle("Tool adding ...")
  3942. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3943. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3944. msgbox.setDefaultButton(bt_ok)
  3945. msgbox.exec_()
  3946. # work only if the notebook tab on focus is the Tools_Tab
  3947. if notebook_widget_name == 'tool_tab':
  3948. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3949. # and only if the tool is NCC Tool
  3950. if tool_widget == self.ncclear_tool.toolName:
  3951. self.ncclear_tool.on_add_tool_by_key()
  3952. # and only if the tool is Paint Area Tool
  3953. elif tool_widget == self.paint_tool.toolName:
  3954. self.paint_tool.on_add_tool_by_key()
  3955. # and only if the tool is Solder Paste Dispensing Tool
  3956. elif tool_widget == self.paste_tool.toolName:
  3957. self.paste_tool.on_add_tool_by_key()
  3958. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3959. # See description below.
  3960. def on_delete_keypress(self):
  3961. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3962. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3963. if notebook_widget_name == 'selected_tab':
  3964. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3965. self.collection.get_active().on_tool_delete()
  3966. # work only if the notebook tab on focus is the Tools_Tab
  3967. elif notebook_widget_name == 'tool_tab':
  3968. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3969. # and only if the tool is NCC Tool
  3970. if tool_widget == self.ncclear_tool.toolName:
  3971. self.ncclear_tool.on_tool_delete()
  3972. # and only if the tool is Paint Tool
  3973. elif tool_widget == self.paint_tool.toolName:
  3974. self.paint_tool.on_tool_delete()
  3975. # and only if the tool is Solder Paste Dispensing Tool
  3976. elif tool_widget == self.paste_tool.toolName:
  3977. self.paste_tool.on_tool_delete()
  3978. else:
  3979. self.on_delete()
  3980. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3981. # some screens you have to be careful where you hover with your mouse.
  3982. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3983. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3984. # Complicated, I know :)
  3985. def on_delete(self, force_deletion=False):
  3986. """
  3987. Delete the currently selected FlatCAMObjs.
  3988. :param force_deletion: used by Tcl command
  3989. :return: None
  3990. """
  3991. self.defaults.report_usage("on_delete()")
  3992. response = None
  3993. bt_ok = None
  3994. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3995. # a geometry object before we update it.
  3996. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3997. and self.grb_editor.editor_active is False:
  3998. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3999. msgbox = QtWidgets.QMessageBox()
  4000. msgbox.setWindowTitle(_("Delete objects"))
  4001. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4002. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4003. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4004. "the selected objects?"))
  4005. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4006. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4007. msgbox.setDefaultButton(bt_ok)
  4008. msgbox.exec_()
  4009. response = msgbox.clickedButton()
  4010. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4011. response = bt_ok
  4012. if response == bt_ok:
  4013. if self.collection.get_active():
  4014. self.log.debug("App.on_delete()")
  4015. for obj_active in self.collection.get_selected():
  4016. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4017. if obj_active.kind == 'gerber':
  4018. for el in obj_active.mark_shapes:
  4019. obj_active.mark_shapes[el].clear(update=True)
  4020. obj_active.mark_shapes[el].enabled = False
  4021. # obj_active.mark_shapes[el] = None
  4022. del el
  4023. elif isinstance(obj_active, CNCJobObject):
  4024. try:
  4025. obj_active.text_col.enabled = False
  4026. del obj_active.text_col
  4027. obj_active.annotation.clear(update=True)
  4028. del obj_active.annotation
  4029. except AttributeError as e:
  4030. log.debug(
  4031. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4032. )
  4033. while self.collection.get_selected():
  4034. self.delete_first_selected()
  4035. self.inform.emit('%s...' % _("Object(s) deleted"))
  4036. # make sure that the selection shape is deleted, too
  4037. self.delete_selection_shape()
  4038. # if there are no longer objects delete also the exclusion areas shapes
  4039. if not self.collection.get_list():
  4040. self.exc_areas.clear_shapes()
  4041. else:
  4042. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4043. else:
  4044. self.inform.emit(_("Save the work in Editor and try again ..."))
  4045. def delete_first_selected(self):
  4046. # Keep this for later
  4047. try:
  4048. sel_obj = self.collection.get_active()
  4049. name = sel_obj.options["name"]
  4050. isPlotted = sel_obj.options["plot"]
  4051. except AttributeError:
  4052. self.log.debug("Nothing selected for deletion")
  4053. return
  4054. if self.is_legacy is True:
  4055. # Remove plot only if the object was plotted otherwise delaxes will fail
  4056. if isPlotted:
  4057. try:
  4058. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4059. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4060. except Exception as e:
  4061. log.debug("App.delete_first_selected() --> %s" % str(e))
  4062. self.plotcanvas.auto_adjust_axes()
  4063. # Remove from dictionary
  4064. self.collection.delete_active()
  4065. # Clear form
  4066. self.setup_component_editor()
  4067. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4068. def on_set_origin(self):
  4069. """
  4070. Set the origin to the left mouse click position
  4071. :return: None
  4072. """
  4073. # display the message for the user
  4074. # and ask him to click on the desired position
  4075. self.defaults.report_usage("on_set_origin()")
  4076. def origin_replot():
  4077. def worker_task():
  4078. with self.proc_container.new('%s...' % _("Plotting")):
  4079. for obj in self.collection.get_list():
  4080. obj.plot()
  4081. self.plotcanvas.fit_view()
  4082. if self.is_legacy:
  4083. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4084. else:
  4085. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4086. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4087. self.inform.emit(_('Click to set the origin ...'))
  4088. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4089. # first disconnect it as it may have been used by something else
  4090. try:
  4091. self.replot_signal.disconnect()
  4092. except TypeError:
  4093. pass
  4094. self.replot_signal[list].connect(origin_replot)
  4095. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4096. """
  4097. :param event:
  4098. :param location:
  4099. :param noplot:
  4100. :param use_thread:
  4101. :return:
  4102. """
  4103. noplot_sig = noplot
  4104. def worker_task():
  4105. with self.proc_container.new(_("Setting Origin...")):
  4106. obj_list = self.collection.get_list()
  4107. for obj in obj_list:
  4108. obj.offset((x, y))
  4109. self.object_changed.emit(obj)
  4110. # Update the object bounding box options
  4111. a, b, c, d = obj.bounds()
  4112. obj.options['xmin'] = a
  4113. obj.options['ymin'] = b
  4114. obj.options['xmax'] = c
  4115. obj.options['ymax'] = d
  4116. self.inform.emit('[success] %s...' % _('Origin set'))
  4117. for obj in obj_list:
  4118. out_name = obj.options["name"]
  4119. if obj.kind == 'gerber':
  4120. obj.source_file = self.export_gerber(
  4121. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4122. elif obj.kind == 'excellon':
  4123. obj.source_file = self.export_excellon(
  4124. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4125. if noplot_sig is False:
  4126. self.replot_signal.emit([])
  4127. if location is not None:
  4128. if len(location) != 2:
  4129. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4130. return 'fail'
  4131. x, y = location
  4132. if use_thread is True:
  4133. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4134. else:
  4135. worker_task()
  4136. self.should_we_save = True
  4137. return
  4138. if event is not None and event.button == 1:
  4139. if self.is_legacy is False:
  4140. event_pos = event.pos
  4141. else:
  4142. event_pos = (event.xdata, event.ydata)
  4143. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4144. if self.grid_status():
  4145. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4146. else:
  4147. pos = pos_canvas
  4148. x = 0 - pos[0]
  4149. y = 0 - pos[1]
  4150. if use_thread is True:
  4151. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4152. else:
  4153. worker_task()
  4154. self.should_we_save = True
  4155. def on_move2origin(self, use_thread=True):
  4156. """
  4157. Move selected objects to origin.
  4158. :param use_thread: Control if to use threaded operation. Boolean.
  4159. :return:
  4160. """
  4161. def worker_task():
  4162. with self.proc_container.new(_("Moving to Origin...")):
  4163. obj_list = self.collection.get_selected()
  4164. if not obj_list:
  4165. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4166. return
  4167. xminlist = []
  4168. yminlist = []
  4169. # first get a bounding box to fit all
  4170. for obj in obj_list:
  4171. xmin, ymin, xmax, ymax = obj.bounds()
  4172. xminlist.append(xmin)
  4173. yminlist.append(ymin)
  4174. # get the minimum x,y for all objects selected
  4175. x = min(xminlist)
  4176. y = min(yminlist)
  4177. for obj in obj_list:
  4178. obj.offset((-x, -y))
  4179. self.object_changed.emit(obj)
  4180. # Update the object bounding box options
  4181. a, b, c, d = obj.bounds()
  4182. obj.options['xmin'] = a
  4183. obj.options['ymin'] = b
  4184. obj.options['xmax'] = c
  4185. obj.options['ymax'] = d
  4186. for obj in obj_list:
  4187. obj.plot()
  4188. for obj in obj_list:
  4189. out_name = obj.options["name"]
  4190. if obj.kind == 'gerber':
  4191. obj.source_file = self.export_gerber(
  4192. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4193. elif obj.kind == 'excellon':
  4194. obj.source_file = self.export_excellon(
  4195. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4196. self.inform.emit('[success] %s...' % _('Origin set'))
  4197. if use_thread is True:
  4198. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4199. else:
  4200. worker_task()
  4201. self.should_we_save = True
  4202. def on_jump_to(self, custom_location=None, fit_center=True):
  4203. """
  4204. Jump to a location by setting the mouse cursor location.
  4205. :param custom_location: Jump to a specified point. (x, y) tuple.
  4206. :param fit_center: If to fit view. Boolean.
  4207. :return:
  4208. """
  4209. self.defaults.report_usage("on_jump_to()")
  4210. if not custom_location:
  4211. dia_box_location = None
  4212. try:
  4213. dia_box_location = eval(self.clipboard.text())
  4214. except Exception:
  4215. pass
  4216. if type(dia_box_location) == tuple:
  4217. dia_box_location = str(dia_box_location)
  4218. else:
  4219. dia_box_location = None
  4220. # dia_box = Dialog_box(title=_("Jump to ..."),
  4221. # label=_("Enter the coordinates in format X,Y:"),
  4222. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4223. # initial_text=dia_box_location)
  4224. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4225. label=_("Enter the coordinates in format X,Y:"),
  4226. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4227. initial_text=dia_box_location,
  4228. reference=self.defaults['global_jump_ref'])
  4229. if dia_box.ok is True:
  4230. try:
  4231. location = eval(dia_box.location)
  4232. if not isinstance(location, tuple):
  4233. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4234. return
  4235. if dia_box.reference == 'rel':
  4236. rel_x = self.mouse[0] + location[0]
  4237. rel_y = self.mouse[1] + location[1]
  4238. location = (rel_x, rel_y)
  4239. self.defaults['global_jump_ref'] = dia_box.reference
  4240. except Exception:
  4241. return
  4242. else:
  4243. return
  4244. else:
  4245. location = custom_location
  4246. self.jump_signal.emit(location)
  4247. if fit_center:
  4248. self.plotcanvas.fit_center(loc=location)
  4249. cursor = QtGui.QCursor()
  4250. if self.is_legacy is False:
  4251. # I don't know where those differences come from but they are constant for the current
  4252. # execution of the application and they are multiples of a value around 0.0263mm.
  4253. # In a random way sometimes they are more sometimes they are less
  4254. # if units == 'MM':
  4255. # cal_factor = 0.0263
  4256. # else:
  4257. # cal_factor = 0.0263 / 25.4
  4258. cal_location = (location[0], location[1])
  4259. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4260. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4261. j_pos = (
  4262. int(canvas_origin.x() + round(jump_loc[0])),
  4263. int(canvas_origin.y() + round(jump_loc[1]))
  4264. )
  4265. cursor.setPos(j_pos[0], j_pos[1])
  4266. else:
  4267. # find the canvas origin which is in the top left corner
  4268. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4269. # determine the coordinates for the lowest left point of the canvas
  4270. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4271. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4272. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4273. # canvas) and the point (width, height) is in the top-right location
  4274. loc = self.plotcanvas.axes.transData.transform_point(location)
  4275. j_pos = (
  4276. int(x0 + loc[0]),
  4277. int(y0 - loc[1])
  4278. )
  4279. cursor.setPos(j_pos[0], j_pos[1])
  4280. self.plotcanvas.mouse = [location[0], location[1]]
  4281. if self.defaults["global_cursor_color_enabled"] is True:
  4282. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4283. else:
  4284. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4285. if self.grid_status():
  4286. # Update cursor
  4287. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4288. symbol='++', edge_color=self.cursor_color_3D,
  4289. edge_width=self.defaults["global_cursor_width"],
  4290. size=self.defaults["global_cursor_size"])
  4291. # Set the relative position label
  4292. dx = location[0] - float(self.rel_point1[0])
  4293. dy = location[1] - float(self.rel_point1[1])
  4294. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4295. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4296. # # Set the position label
  4297. #
  4298. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4299. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4300. units = self.defaults["units"].lower()
  4301. self.plotcanvas.text_hud.text = \
  4302. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4303. dx, units, dy, units, location[0], units, location[1], units)
  4304. self.inform.emit('[success] %s' % _("Done."))
  4305. return location
  4306. def on_locate(self, obj, fit_center=True):
  4307. """
  4308. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4309. :param obj: The object on which to locate certain points
  4310. :param fit_center: If to fit view. Boolean.
  4311. :return: A point location. (x, y) tuple.
  4312. """
  4313. self.defaults.report_usage("on_locate()")
  4314. if obj is None:
  4315. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4316. return 'fail'
  4317. class DialogBoxChoice(QtWidgets.QDialog):
  4318. def __init__(self, title=None, icon=None, choice='bl'):
  4319. """
  4320. :param title: string with the window title
  4321. """
  4322. super(DialogBoxChoice, self).__init__()
  4323. self.ok = False
  4324. self.setWindowIcon(icon)
  4325. self.setWindowTitle(str(title))
  4326. self.form = QtWidgets.QFormLayout(self)
  4327. self.ref_radio = RadioSet([
  4328. {"label": _("Bottom-Left"), "value": "bl"},
  4329. {"label": _("Top-Left"), "value": "tl"},
  4330. {"label": _("Bottom-Right"), "value": "br"},
  4331. {"label": _("Top-Right"), "value": "tr"},
  4332. {"label": _("Center"), "value": "c"}
  4333. ], orientation='vertical', stretch=False)
  4334. self.ref_radio.set_value(choice)
  4335. self.form.addRow(self.ref_radio)
  4336. self.button_box = QtWidgets.QDialogButtonBox(
  4337. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4338. Qt.Horizontal, parent=self)
  4339. self.form.addRow(self.button_box)
  4340. self.button_box.accepted.connect(self.accept)
  4341. self.button_box.rejected.connect(self.reject)
  4342. if self.exec_() == QtWidgets.QDialog.Accepted:
  4343. self.ok = True
  4344. self.location_point = self.ref_radio.get_value()
  4345. else:
  4346. self.ok = False
  4347. self.location_point = None
  4348. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4349. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4350. choice=self.defaults['global_locate_pt'])
  4351. if dia_box.ok is True:
  4352. try:
  4353. location_point = dia_box.location_point
  4354. self.defaults['global_locate_pt'] = dia_box.location_point
  4355. except Exception:
  4356. return
  4357. else:
  4358. return
  4359. loc_b = obj.bounds()
  4360. if location_point == 'bl':
  4361. location = (loc_b[0], loc_b[1])
  4362. elif location_point == 'tl':
  4363. location = (loc_b[0], loc_b[3])
  4364. elif location_point == 'br':
  4365. location = (loc_b[2], loc_b[1])
  4366. elif location_point == 'tr':
  4367. location = (loc_b[2], loc_b[3])
  4368. else:
  4369. # center
  4370. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4371. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4372. location = (cx, cy)
  4373. self.locate_signal.emit(location, location_point)
  4374. if fit_center:
  4375. self.plotcanvas.fit_center(loc=location)
  4376. cursor = QtGui.QCursor()
  4377. if self.is_legacy is False:
  4378. # I don't know where those differences come from but they are constant for the current
  4379. # execution of the application and they are multiples of a value around 0.0263mm.
  4380. # In a random way sometimes they are more sometimes they are less
  4381. # if units == 'MM':
  4382. # cal_factor = 0.0263
  4383. # else:
  4384. # cal_factor = 0.0263 / 25.4
  4385. cal_location = (location[0], location[1])
  4386. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4387. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4388. j_pos = (
  4389. int(canvas_origin.x() + round(jump_loc[0])),
  4390. int(canvas_origin.y() + round(jump_loc[1]))
  4391. )
  4392. cursor.setPos(j_pos[0], j_pos[1])
  4393. else:
  4394. # find the canvas origin which is in the top left corner
  4395. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4396. # determine the coordinates for the lowest left point of the canvas
  4397. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4398. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4399. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4400. # canvas) and the point (width, height) is in the top-right location
  4401. loc = self.plotcanvas.axes.transData.transform_point(location)
  4402. j_pos = (
  4403. int(x0 + loc[0]),
  4404. int(y0 - loc[1])
  4405. )
  4406. cursor.setPos(j_pos[0], j_pos[1])
  4407. self.plotcanvas.mouse = [location[0], location[1]]
  4408. if self.defaults["global_cursor_color_enabled"] is True:
  4409. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4410. else:
  4411. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4412. if self.grid_status():
  4413. # Update cursor
  4414. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4415. symbol='++', edge_color=self.cursor_color_3D,
  4416. edge_width=self.defaults["global_cursor_width"],
  4417. size=self.defaults["global_cursor_size"])
  4418. # Set the relative position label
  4419. self.dx = location[0] - float(self.rel_point1[0])
  4420. self.dy = location[1] - float(self.rel_point1[1])
  4421. # Set the position label
  4422. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4423. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4424. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4425. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4426. units = self.defaults["units"].lower()
  4427. self.plotcanvas.text_hud.text = \
  4428. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4429. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4430. self.inform.emit('[success] %s' % _("Done."))
  4431. return location
  4432. def on_copy_command(self):
  4433. """
  4434. Will copy a selection of objects, creating new objects.
  4435. :return:
  4436. """
  4437. self.defaults.report_usage("on_copy_command()")
  4438. def initialize(obj_init, app):
  4439. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4440. try:
  4441. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4442. except AttributeError:
  4443. pass
  4444. try:
  4445. obj_init.apertures = deepcopy(obj.apertures)
  4446. except AttributeError:
  4447. pass
  4448. try:
  4449. if obj.tools:
  4450. obj_init.tools = deepcopy(obj.tools)
  4451. except Exception as err:
  4452. log.debug("App.on_copy_command() --> %s" % str(err))
  4453. try:
  4454. obj_init.source_file = deepcopy(obj.source_file)
  4455. except (AttributeError, TypeError):
  4456. pass
  4457. def initialize_excellon(obj_init, app):
  4458. obj_init.source_file = deepcopy(obj.source_file)
  4459. obj_init.tools = deepcopy(obj.tools)
  4460. # drills are offset, so they need to be deep copied
  4461. obj_init.drills = deepcopy(obj.drills)
  4462. # slots are offset, so they need to be deep copied
  4463. obj_init.slots = deepcopy(obj.slots)
  4464. obj_init.create_geometry()
  4465. def initialize_script(obj_init, app_obj):
  4466. obj_init.source_file = deepcopy(obj.source_file)
  4467. def initialize_document(obj_init, app_obj):
  4468. obj_init.source_file = deepcopy(obj.source_file)
  4469. for obj in self.collection.get_selected():
  4470. obj_name = obj.options["name"]
  4471. try:
  4472. if isinstance(obj, ExcellonObject):
  4473. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4474. elif isinstance(obj, GerberObject):
  4475. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4476. elif isinstance(obj, GeometryObject):
  4477. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4478. elif isinstance(obj, ScriptObject):
  4479. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4480. elif isinstance(obj, DocumentObject):
  4481. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4482. except Exception as e:
  4483. return "Operation failed: %s" % str(e)
  4484. def on_copy_object2(self, custom_name):
  4485. def initialize_geometry(obj_init, app):
  4486. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4487. try:
  4488. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4489. except AttributeError:
  4490. pass
  4491. try:
  4492. obj_init.apertures = deepcopy(obj.apertures)
  4493. except AttributeError:
  4494. pass
  4495. try:
  4496. if obj.tools:
  4497. obj_init.tools = deepcopy(obj.tools)
  4498. except Exception as ee:
  4499. log.debug("on_copy_object2() --> %s" % str(ee))
  4500. def initialize_gerber(obj_init, app):
  4501. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4502. obj_init.apertures = deepcopy(obj.apertures)
  4503. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4504. def initialize_excellon(obj_init, app):
  4505. obj_init.tools = deepcopy(obj.tools)
  4506. # drills are offset, so they need to be deep copied
  4507. obj_init.drills = deepcopy(obj.drills)
  4508. # slots are offset, so they need to be deep copied
  4509. obj_init.slots = deepcopy(obj.slots)
  4510. obj_init.create_geometry()
  4511. for obj in self.collection.get_selected():
  4512. obj_name = obj.options["name"]
  4513. try:
  4514. if isinstance(obj, ExcellonObject):
  4515. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4516. elif isinstance(obj, GerberObject):
  4517. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4518. elif isinstance(obj, GeometryObject):
  4519. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4520. except Exception as er:
  4521. return "Operation failed: %s" % str(er)
  4522. def on_rename_object(self, text):
  4523. """
  4524. Will rename an object.
  4525. :param text: New name for the object.
  4526. :return:
  4527. """
  4528. self.defaults.report_usage("on_rename_object()")
  4529. named_obj = self.collection.get_active()
  4530. for obj in named_obj:
  4531. if obj is list:
  4532. self.on_rename_object(text)
  4533. else:
  4534. try:
  4535. obj.options['name'] = text
  4536. except Exception as e:
  4537. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4538. def convert_any2geo(self):
  4539. """
  4540. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4541. :return:
  4542. """
  4543. self.defaults.report_usage("convert_any2geo()")
  4544. def initialize(obj_init, app):
  4545. obj_init.solid_geometry = obj.solid_geometry
  4546. try:
  4547. obj_init.follow_geometry = obj.follow_geometry
  4548. except AttributeError:
  4549. pass
  4550. try:
  4551. obj_init.apertures = obj.apertures
  4552. except AttributeError:
  4553. pass
  4554. try:
  4555. if obj.tools:
  4556. obj_init.tools = obj.tools
  4557. except AttributeError:
  4558. pass
  4559. def initialize_excellon(obj_init, app):
  4560. # objs = self.collection.get_selected()
  4561. # GeometryObject.merge(objs, obj)
  4562. solid_geo = []
  4563. for tool in obj.tools:
  4564. for geo in obj.tools[tool]['solid_geometry']:
  4565. solid_geo.append(geo)
  4566. obj_init.solid_geometry = deepcopy(solid_geo)
  4567. if not self.collection.get_selected():
  4568. log.warning("App.convert_any2geo --> No object selected")
  4569. self.inform.emit('[WARNING_NOTCL] %s' %
  4570. _("No object is selected. Select an object and try again."))
  4571. return
  4572. for obj in self.collection.get_selected():
  4573. obj_name = obj.options["name"]
  4574. try:
  4575. if isinstance(obj, ExcellonObject):
  4576. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4577. else:
  4578. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4579. except Exception as e:
  4580. return "Operation failed: %s" % str(e)
  4581. def convert_any2gerber(self):
  4582. """
  4583. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4584. :return:
  4585. """
  4586. self.defaults.report_usage("convert_any2gerber()")
  4587. def initialize_geometry(obj_init, app):
  4588. apertures = {}
  4589. apid = 0
  4590. apertures[str(apid)] = {}
  4591. apertures[str(apid)]['geometry'] = []
  4592. for obj_orig in obj.solid_geometry:
  4593. new_elem = {}
  4594. new_elem['solid'] = obj_orig
  4595. try:
  4596. new_elem['follow'] = obj_orig.exterior
  4597. except AttributeError:
  4598. pass
  4599. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4600. apertures[str(apid)]['size'] = 0.0
  4601. apertures[str(apid)]['type'] = 'C'
  4602. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4603. obj_init.apertures = deepcopy(apertures)
  4604. def initialize_excellon(obj_init, app):
  4605. apertures = {}
  4606. apid = 10
  4607. for tool in obj.tools:
  4608. apertures[str(apid)] = {}
  4609. apertures[str(apid)]['geometry'] = []
  4610. for geo in obj.tools[tool]['solid_geometry']:
  4611. new_el = {}
  4612. new_el['solid'] = geo
  4613. new_el['follow'] = geo.exterior
  4614. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4615. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4616. apertures[str(apid)]['type'] = 'C'
  4617. apid += 1
  4618. # create solid_geometry
  4619. solid_geometry = []
  4620. for apid in apertures:
  4621. for geo_el in apertures[apid]['geometry']:
  4622. solid_geometry.append(geo_el['solid'])
  4623. solid_geometry = MultiPolygon(solid_geometry)
  4624. solid_geometry = solid_geometry.buffer(0.0000001)
  4625. obj_init.solid_geometry = deepcopy(solid_geometry)
  4626. obj_init.apertures = deepcopy(apertures)
  4627. # clear the working objects (perhaps not necessary due of Python GC)
  4628. apertures.clear()
  4629. if not self.collection.get_selected():
  4630. log.warning("App.convert_any2gerber --> No object selected")
  4631. self.inform.emit('[WARNING_NOTCL] %s' %
  4632. _("No object is selected. Select an object and try again."))
  4633. return
  4634. for obj in self.collection.get_selected():
  4635. obj_name = obj.options["name"]
  4636. try:
  4637. if isinstance(obj, ExcellonObject):
  4638. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4639. elif isinstance(obj, GeometryObject):
  4640. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4641. else:
  4642. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4643. except Exception as e:
  4644. return "Operation failed: %s" % str(e)
  4645. def abort_all_tasks(self):
  4646. """
  4647. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4648. on the first possible occasion.
  4649. :return:
  4650. """
  4651. if self.abort_flag is False:
  4652. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4653. self.abort_flag = True
  4654. self.cleanup.emit()
  4655. def app_is_idle(self):
  4656. if self.abort_flag:
  4657. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4658. self.abort_flag = False
  4659. def on_selectall(self):
  4660. """
  4661. Will draw a selection box shape around the selected objects.
  4662. :return:
  4663. """
  4664. self.defaults.report_usage("on_selectall()")
  4665. # delete the possible selection box around a possible selected object
  4666. self.delete_selection_shape()
  4667. for name in self.collection.get_names():
  4668. self.collection.set_active(name)
  4669. curr_sel_obj = self.collection.get_by_name(name)
  4670. # create the selection box around the selected object
  4671. if self.defaults['global_selection_shape'] is True:
  4672. self.draw_selection_shape(curr_sel_obj)
  4673. def on_preferences(self):
  4674. """
  4675. Adds the Preferences in a Tab in Plot Area
  4676. :return:
  4677. """
  4678. # add the tab if it was closed
  4679. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4680. # delete the absolute and relative position and messages in the infobar
  4681. self.ui.position_label.setText("")
  4682. # self.ui.rel_position_label.setText("")
  4683. # Switch plot_area to preferences page
  4684. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4685. # self.ui.show()
  4686. # detect changes in the preferences
  4687. for idx in range(self.ui.pref_tab_area.count()):
  4688. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4689. try:
  4690. try:
  4691. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4692. except (TypeError, AttributeError):
  4693. pass
  4694. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4695. except AttributeError:
  4696. pass
  4697. try:
  4698. try:
  4699. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4700. except (TypeError, AttributeError):
  4701. pass
  4702. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4703. except AttributeError:
  4704. pass
  4705. try:
  4706. try:
  4707. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4708. except (TypeError, AttributeError):
  4709. pass
  4710. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4711. except AttributeError:
  4712. pass
  4713. try:
  4714. try:
  4715. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4716. except (TypeError, AttributeError):
  4717. pass
  4718. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4719. except AttributeError:
  4720. pass
  4721. try:
  4722. try:
  4723. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4724. except (TypeError, AttributeError):
  4725. pass
  4726. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4727. except AttributeError:
  4728. pass
  4729. def on_tools_database(self, source='app'):
  4730. """
  4731. Adds the Tools Database in a Tab in Plot Area.
  4732. :return:
  4733. """
  4734. for idx in range(self.ui.plot_tab_area.count()):
  4735. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4736. # there can be only one instance of Tools Database at one time
  4737. return
  4738. if source == 'app':
  4739. self.tools_db_tab = ToolsDB2(
  4740. app=self,
  4741. parent=self.ui,
  4742. callback_on_edited=self.on_tools_db_edited,
  4743. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4744. )
  4745. elif source == 'ncc':
  4746. self.tools_db_tab = ToolsDB2(
  4747. app=self,
  4748. parent=self.ui,
  4749. callback_on_edited=self.on_tools_db_edited,
  4750. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4751. )
  4752. elif source == 'paint':
  4753. self.tools_db_tab = ToolsDB2(
  4754. app=self,
  4755. parent=self.ui,
  4756. callback_on_edited=self.on_tools_db_edited,
  4757. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4758. )
  4759. # add the tab if it was closed
  4760. try:
  4761. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4762. self.tools_db_tab.setObjectName("database_tab")
  4763. except Exception as e:
  4764. log.debug("App.on_tools_database() --> %s" % str(e))
  4765. return
  4766. # delete the absolute and relative position and messages in the infobar
  4767. self.ui.position_label.setText("")
  4768. # self.ui.rel_position_label.setText("")
  4769. # Switch plot_area to preferences page
  4770. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4771. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4772. self.tools_db_tab.ui_connect()
  4773. def on_tools_db_edited(self):
  4774. """
  4775. Executed whenever a tool is edited in Tools Database.
  4776. Will color the text of the Tools Database tab to Red color.
  4777. :return:
  4778. """
  4779. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4780. for idx in range(self.ui.plot_tab_area.count()):
  4781. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4782. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4783. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4784. self.tools_db_changed_flag = True
  4785. def on_geometry_tool_add_from_db_executed(self, tool):
  4786. """
  4787. Here add the tool from DB in the selected geometry object.
  4788. :return:
  4789. """
  4790. tool_from_db = deepcopy(tool)
  4791. obj = self.collection.get_active()
  4792. if isinstance(obj, GeometryObject):
  4793. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4794. # close the tab and delete it
  4795. for idx in range(self.ui.plot_tab_area.count()):
  4796. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4797. wdg = self.ui.plot_tab_area.widget(idx)
  4798. wdg.deleteLater()
  4799. self.ui.plot_tab_area.removeTab(idx)
  4800. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4801. else:
  4802. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4803. def on_plot_area_tab_closed(self, tab_obj_name):
  4804. """
  4805. Executed whenever a QTab is closed in the Plot Area.
  4806. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4807. :return:
  4808. """
  4809. if tab_obj_name == "preferences_tab":
  4810. self.preferencesUiManager.on_close_preferences_tab()
  4811. elif tab_obj_name == "database_tab":
  4812. # disconnect the signals from the table widget in tab
  4813. self.tools_db_tab.ui_disconnect()
  4814. if self.tools_db_changed_flag is True:
  4815. msgbox = QtWidgets.QMessageBox()
  4816. msgbox.setText(_("One or more Tools are edited.\n"
  4817. "Do you want to update the Tools Database?"))
  4818. msgbox.setWindowTitle(_("Save Tools Database"))
  4819. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4820. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4821. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4822. msgbox.setDefaultButton(bt_yes)
  4823. msgbox.exec_()
  4824. response = msgbox.clickedButton()
  4825. if response == bt_yes:
  4826. self.tools_db_tab.on_save_tools_db()
  4827. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4828. else:
  4829. self.tools_db_changed_flag = False
  4830. self.inform.emit('')
  4831. return
  4832. self.tools_db_tab.deleteLater()
  4833. elif tab_obj_name == "text_editor_tab":
  4834. self.toggle_codeeditor = False
  4835. elif tab_obj_name == "bookmarks_tab":
  4836. self.book_dialog_tab.rebuild_actions()
  4837. self.book_dialog_tab.deleteLater()
  4838. else:
  4839. return
  4840. # def on_plotarea_tab_closed(self, tab_idx):
  4841. # """
  4842. #
  4843. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4844. # :return:
  4845. # """
  4846. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4847. #
  4848. # if widget is not None:
  4849. # widget.deleteLater()
  4850. # self.ui.plot_tab_area.removeTab(tab_idx)
  4851. def on_flipy(self):
  4852. """
  4853. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4854. :return:
  4855. """
  4856. self.defaults.report_usage("on_flipy()")
  4857. obj_list = self.collection.get_selected()
  4858. xminlist = []
  4859. yminlist = []
  4860. xmaxlist = []
  4861. ymaxlist = []
  4862. if not obj_list:
  4863. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4864. else:
  4865. try:
  4866. # first get a bounding box to fit all
  4867. for obj in obj_list:
  4868. xmin, ymin, xmax, ymax = obj.bounds()
  4869. xminlist.append(xmin)
  4870. yminlist.append(ymin)
  4871. xmaxlist.append(xmax)
  4872. ymaxlist.append(ymax)
  4873. # get the minimum x,y and maximum x,y for all objects selected
  4874. xminimal = min(xminlist)
  4875. yminimal = min(yminlist)
  4876. xmaximal = max(xmaxlist)
  4877. ymaximal = max(ymaxlist)
  4878. px = 0.5 * (xminimal + xmaximal)
  4879. py = 0.5 * (yminimal + ymaximal)
  4880. # execute mirroring
  4881. for obj in obj_list:
  4882. obj.mirror('X', [px, py])
  4883. obj.plot()
  4884. self.object_changed.emit(obj)
  4885. self.inform.emit('[success] %s' %
  4886. _("Flip on Y axis done."))
  4887. except Exception as e:
  4888. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4889. return
  4890. def on_flipx(self):
  4891. """
  4892. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4893. :return:
  4894. """
  4895. self.defaults.report_usage("on_flipx()")
  4896. obj_list = self.collection.get_selected()
  4897. xminlist = []
  4898. yminlist = []
  4899. xmaxlist = []
  4900. ymaxlist = []
  4901. if not obj_list:
  4902. self.inform.emit('[WARNING_NOTCL] %s' %
  4903. _("No object selected to Flip on X axis."))
  4904. else:
  4905. try:
  4906. # first get a bounding box to fit all
  4907. for obj in obj_list:
  4908. xmin, ymin, xmax, ymax = obj.bounds()
  4909. xminlist.append(xmin)
  4910. yminlist.append(ymin)
  4911. xmaxlist.append(xmax)
  4912. ymaxlist.append(ymax)
  4913. # get the minimum x,y and maximum x,y for all objects selected
  4914. xminimal = min(xminlist)
  4915. yminimal = min(yminlist)
  4916. xmaximal = max(xmaxlist)
  4917. ymaximal = max(ymaxlist)
  4918. px = 0.5 * (xminimal + xmaximal)
  4919. py = 0.5 * (yminimal + ymaximal)
  4920. # execute mirroring
  4921. for obj in obj_list:
  4922. obj.mirror('Y', [px, py])
  4923. obj.plot()
  4924. self.object_changed.emit(obj)
  4925. self.inform.emit('[success] %s' %
  4926. _("Flip on X axis done."))
  4927. except Exception as e:
  4928. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4929. return
  4930. def on_rotate(self, silent=False, preset=None):
  4931. """
  4932. Executed when Options -> Rotate Selection menu entry is clicked.
  4933. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4934. :param preset: A value to be used as predefined angle for rotation.
  4935. :return:
  4936. """
  4937. self.defaults.report_usage("on_rotate()")
  4938. obj_list = self.collection.get_selected()
  4939. xminlist = []
  4940. yminlist = []
  4941. xmaxlist = []
  4942. ymaxlist = []
  4943. if not obj_list:
  4944. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4945. else:
  4946. if silent is False:
  4947. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4948. min=-360, max=360, decimals=4,
  4949. init_val=float(self.defaults['tools_transform_rotate']))
  4950. num, ok = rotatebox.get_value()
  4951. else:
  4952. num = preset
  4953. ok = True
  4954. if ok:
  4955. try:
  4956. # first get a bounding box to fit all
  4957. for obj in obj_list:
  4958. xmin, ymin, xmax, ymax = obj.bounds()
  4959. xminlist.append(xmin)
  4960. yminlist.append(ymin)
  4961. xmaxlist.append(xmax)
  4962. ymaxlist.append(ymax)
  4963. # get the minimum x,y and maximum x,y for all objects selected
  4964. xminimal = min(xminlist)
  4965. yminimal = min(yminlist)
  4966. xmaximal = max(xmaxlist)
  4967. ymaximal = max(ymaxlist)
  4968. px = 0.5 * (xminimal + xmaximal)
  4969. py = 0.5 * (yminimal + ymaximal)
  4970. for sel_obj in obj_list:
  4971. sel_obj.rotate(-float(num), point=(px, py))
  4972. sel_obj.plot()
  4973. self.object_changed.emit(sel_obj)
  4974. self.inform.emit('[success] %s' %
  4975. _("Rotation done."))
  4976. except Exception as e:
  4977. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4978. return
  4979. def on_skewx(self):
  4980. """
  4981. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4982. :return:
  4983. """
  4984. self.defaults.report_usage("on_skewx()")
  4985. obj_list = self.collection.get_selected()
  4986. xminlist = []
  4987. yminlist = []
  4988. if not obj_list:
  4989. self.inform.emit('[WARNING_NOTCL] %s' %
  4990. _("No object selected to Skew/Shear on X axis."))
  4991. else:
  4992. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4993. min=-360, max=360, decimals=4,
  4994. init_val=float(self.defaults['tools_transform_skew_x']))
  4995. num, ok = skewxbox.get_value()
  4996. if ok:
  4997. # first get a bounding box to fit all
  4998. for obj in obj_list:
  4999. xmin, ymin, xmax, ymax = obj.bounds()
  5000. xminlist.append(xmin)
  5001. yminlist.append(ymin)
  5002. # get the minimum x,y and maximum x,y for all objects selected
  5003. xminimal = min(xminlist)
  5004. yminimal = min(yminlist)
  5005. for obj in obj_list:
  5006. obj.skew(num, 0, point=(xminimal, yminimal))
  5007. obj.plot()
  5008. self.object_changed.emit(obj)
  5009. self.inform.emit('[success] %s' %
  5010. _("Skew on X axis done."))
  5011. def on_skewy(self):
  5012. """
  5013. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5014. :return:
  5015. """
  5016. self.defaults.report_usage("on_skewy()")
  5017. obj_list = self.collection.get_selected()
  5018. xminlist = []
  5019. yminlist = []
  5020. if not obj_list:
  5021. self.inform.emit('[WARNING_NOTCL] %s' %
  5022. _("No object selected to Skew/Shear on Y axis."))
  5023. else:
  5024. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5025. min=-360, max=360, decimals=4,
  5026. init_val=float(self.defaults['tools_transform_skew_y']))
  5027. num, ok = skewybox.get_value()
  5028. if ok:
  5029. # first get a bounding box to fit all
  5030. for obj in obj_list:
  5031. xmin, ymin, xmax, ymax = obj.bounds()
  5032. xminlist.append(xmin)
  5033. yminlist.append(ymin)
  5034. # get the minimum x,y and maximum x,y for all objects selected
  5035. xminimal = min(xminlist)
  5036. yminimal = min(yminlist)
  5037. for obj in obj_list:
  5038. obj.skew(0, num, point=(xminimal, yminimal))
  5039. obj.plot()
  5040. self.object_changed.emit(obj)
  5041. self.inform.emit('[success] %s' %
  5042. _("Skew on Y axis done."))
  5043. def on_plots_updated(self):
  5044. """
  5045. Callback used to report when the plots have changed.
  5046. Adjust axes and zooms to fit.
  5047. :return: None
  5048. """
  5049. if self.is_legacy is False:
  5050. self.plotcanvas.update()
  5051. else:
  5052. self.plotcanvas.auto_adjust_axes()
  5053. self.on_zoom_fit(None)
  5054. self.collection.update_view()
  5055. # self.inform.emit(_("Plots updated ..."))
  5056. def on_toolbar_replot(self):
  5057. """
  5058. Callback for toolbar button. Re-plots all objects.
  5059. :return: None
  5060. """
  5061. self.defaults.report_usage("on_toolbar_replot")
  5062. self.log.debug("on_toolbar_replot()")
  5063. try:
  5064. self.collection.get_active().read_form()
  5065. except AttributeError:
  5066. self.log.debug("on_toolbar_replot(): AttributeError")
  5067. pass
  5068. self.plot_all()
  5069. def on_row_activated(self, index):
  5070. if index.isValid():
  5071. if index.internalPointer().parent_item != self.collection.root_item:
  5072. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5073. self.collection.on_item_activated(index)
  5074. def on_row_selected(self, obj_name):
  5075. """
  5076. This is a special string; when received it will make all Menu -> AppObjects entries unchecked
  5077. It mean we clicked outside of the items and deselected all
  5078. :param obj_name:
  5079. :return:
  5080. """
  5081. if obj_name == 'none':
  5082. for act in self.ui.menuobjects.actions():
  5083. act.setChecked(False)
  5084. return
  5085. # get the name of the selected objects and add them to a list
  5086. name_list = []
  5087. for obj in self.collection.get_selected():
  5088. name_list.append(obj.options['name'])
  5089. # set all actions as unchecked but the ones selected make them checked
  5090. for act in self.ui.menuobjects.actions():
  5091. act.setChecked(False)
  5092. if act.text() in name_list:
  5093. act.setChecked(True)
  5094. def on_collection_updated(self, obj, state, old_name):
  5095. """
  5096. Create a menu from the object loaded in the collection.
  5097. :param obj: object that was changed (added, deleted, renamed)
  5098. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5099. :param old_name: the old name of the object before the action that triggered this slot happened
  5100. :return: None
  5101. """
  5102. icon_files = {
  5103. "gerber": self.resource_location + "/flatcam_icon16.png",
  5104. "excellon": self.resource_location + "/drill16.png",
  5105. "cncjob": self.resource_location + "/cnc16.png",
  5106. "geometry": self.resource_location + "/geometry16.png",
  5107. "script": self.resource_location + "/script_new16.png",
  5108. "document": self.resource_location + "/notes16_1.png"
  5109. }
  5110. if state == 'append':
  5111. for act in self.ui.menuobjects.actions():
  5112. try:
  5113. act.triggered.disconnect()
  5114. except TypeError:
  5115. pass
  5116. self.ui.menuobjects.clear()
  5117. gerber_list = []
  5118. exc_list = []
  5119. cncjob_list = []
  5120. geo_list = []
  5121. script_list = []
  5122. doc_list = []
  5123. for name in self.collection.get_names():
  5124. obj_named = self.collection.get_by_name(name)
  5125. if obj_named.kind == 'gerber':
  5126. gerber_list.append(name)
  5127. elif obj_named.kind == 'excellon':
  5128. exc_list.append(name)
  5129. elif obj_named.kind == 'cncjob':
  5130. cncjob_list.append(name)
  5131. elif obj_named.kind == 'geometry':
  5132. geo_list.append(name)
  5133. elif obj_named.kind == 'script':
  5134. script_list.append(name)
  5135. elif obj_named.kind == 'document':
  5136. doc_list.append(name)
  5137. def add_act(o_name):
  5138. obj_for_icon = self.collection.get_by_name(o_name)
  5139. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5140. add_action.setCheckable(True)
  5141. add_action.setText(o_name)
  5142. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5143. add_action.triggered.connect(
  5144. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5145. self.collection.set_inactive(o_name))
  5146. self.ui.menuobjects.addAction(add_action)
  5147. for name in gerber_list:
  5148. add_act(name)
  5149. self.ui.menuobjects.addSeparator()
  5150. for name in exc_list:
  5151. add_act(name)
  5152. self.ui.menuobjects.addSeparator()
  5153. for name in cncjob_list:
  5154. add_act(name)
  5155. self.ui.menuobjects.addSeparator()
  5156. for name in geo_list:
  5157. add_act(name)
  5158. self.ui.menuobjects.addSeparator()
  5159. for name in script_list:
  5160. add_act(name)
  5161. self.ui.menuobjects.addSeparator()
  5162. for name in doc_list:
  5163. add_act(name)
  5164. self.ui.menuobjects.addSeparator()
  5165. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5166. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5167. _('Select All')
  5168. )
  5169. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5170. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5171. _('Deselect All')
  5172. )
  5173. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5174. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5175. elif state == 'delete':
  5176. for act in self.ui.menuobjects.actions():
  5177. if act.text() == obj.options['name']:
  5178. try:
  5179. act.triggered.disconnect()
  5180. except TypeError:
  5181. pass
  5182. self.ui.menuobjects.removeAction(act)
  5183. break
  5184. elif state == 'rename':
  5185. for act in self.ui.menuobjects.actions():
  5186. if act.text() == old_name:
  5187. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5188. add_action.setText(obj.options['name'])
  5189. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5190. add_action.triggered.connect(
  5191. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5192. self.collection.set_inactive(obj.options['name']))
  5193. self.ui.menuobjects.insertAction(act, add_action)
  5194. try:
  5195. act.triggered.disconnect()
  5196. except TypeError:
  5197. pass
  5198. self.ui.menuobjects.removeAction(act)
  5199. break
  5200. elif state == 'delete_all':
  5201. for act in self.ui.menuobjects.actions():
  5202. try:
  5203. act.triggered.disconnect()
  5204. except TypeError:
  5205. pass
  5206. self.ui.menuobjects.clear()
  5207. self.ui.menuobjects.addSeparator()
  5208. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5209. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5210. _('Select All')
  5211. )
  5212. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5213. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5214. _('Deselect All')
  5215. )
  5216. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5217. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5218. def on_objects_selection(self, on_off):
  5219. obj_list = self.collection.get_names()
  5220. if on_off is True:
  5221. self.collection.set_all_active()
  5222. for act in self.ui.menuobjects.actions():
  5223. try:
  5224. act.setChecked(True)
  5225. except Exception:
  5226. pass
  5227. if obj_list:
  5228. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5229. else:
  5230. self.collection.set_all_inactive()
  5231. for act in self.ui.menuobjects.actions():
  5232. try:
  5233. act.setChecked(False)
  5234. except Exception:
  5235. pass
  5236. if obj_list:
  5237. self.inform.emit('%s' % _("AppObjects selection is cleared."))
  5238. else:
  5239. self.inform.emit('')
  5240. def grid_status(self):
  5241. return True if self.ui.grid_snap_btn.isChecked() else False
  5242. def populate_cmenu_grids(self):
  5243. units = self.defaults['units'].lower()
  5244. # for act in self.ui.cmenu_gridmenu.actions():
  5245. # act.triggered.disconnect()
  5246. self.ui.cmenu_gridmenu.clear()
  5247. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5248. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5249. _("Grid On/Off"))
  5250. grid_toggle.setCheckable(True)
  5251. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5252. self.ui.cmenu_gridmenu.addSeparator()
  5253. for grid in sorted_list:
  5254. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5255. "%s" % str(grid))
  5256. action.triggered.connect(self.set_grid)
  5257. self.ui.cmenu_gridmenu.addSeparator()
  5258. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5259. _("Add"))
  5260. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5261. _("Delete"))
  5262. grid_add.triggered.connect(self.on_grid_add)
  5263. grid_delete.triggered.connect(self.on_grid_delete)
  5264. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5265. def set_grid(self):
  5266. menu_action = self.sender()
  5267. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5268. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5269. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5270. def on_grid_add(self):
  5271. # ## Current application units in lower Case
  5272. units = self.defaults['units'].lower()
  5273. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5274. text=_('Enter a Grid Value:'),
  5275. min=0.0000, max=99.9999, decimals=4)
  5276. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5277. val, ok = grid_add_popup.get_value()
  5278. if ok:
  5279. if float(val) == 0:
  5280. self.inform.emit('[WARNING_NOTCL] %s' %
  5281. _("Please enter a grid value with non-zero value, in Float format."))
  5282. return
  5283. else:
  5284. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5285. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5286. self.inform.emit('[success] %s...' % _("New Grid added"))
  5287. else:
  5288. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  5289. else:
  5290. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  5291. def on_grid_delete(self):
  5292. # ## Current application units in lower Case
  5293. units = self.defaults['units'].lower()
  5294. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5295. text='Enter a Grid Value:',
  5296. min=0.0000, max=99.9999, decimals=4)
  5297. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5298. val, ok = grid_del_popup.get_value()
  5299. if ok:
  5300. if float(val) == 0:
  5301. self.inform.emit('[WARNING_NOTCL] %s' %
  5302. _("Please enter a grid value with non-zero value, in Float format."))
  5303. return
  5304. else:
  5305. try:
  5306. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5307. except ValueError:
  5308. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  5309. return
  5310. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  5311. else:
  5312. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  5313. def on_shortcut_list(self):
  5314. self.defaults.report_usage("on_shortcut_list()")
  5315. # add the tab if it was closed
  5316. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5317. # delete the absolute and relative position and messages in the infobar
  5318. self.ui.position_label.setText("")
  5319. # self.ui.rel_position_label.setText("")
  5320. # Switch plot_area to preferences page
  5321. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5322. # self.ui.show()
  5323. def on_select_tab(self, name):
  5324. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5325. if self.ui.splitter.sizes()[0] == 0:
  5326. self.ui.splitter.setSizes([1, 1])
  5327. else:
  5328. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5329. self.ui.splitter.setSizes([0, 1])
  5330. if name == 'project':
  5331. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5332. elif name == 'selected':
  5333. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5334. elif name == 'tool':
  5335. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5336. def on_copy_name(self):
  5337. self.defaults.report_usage("on_copy_name()")
  5338. obj = self.collection.get_active()
  5339. try:
  5340. name = obj.options["name"]
  5341. except AttributeError:
  5342. log.debug("on_copy_name() --> No object selected to copy it's name")
  5343. self.inform.emit('[WARNING_NOTCL]%s' %
  5344. _(" No object selected to copy it's name"))
  5345. return
  5346. self.clipboard.setText(name)
  5347. self.inform.emit(_("Name copied on clipboard ..."))
  5348. def on_mouse_click_over_plot(self, event):
  5349. """
  5350. Default actions are:
  5351. :param event: Contains information about the event, like which button
  5352. was clicked, the pixel coordinates and the axes coordinates.
  5353. :return: None
  5354. """
  5355. self.pos = []
  5356. if self.is_legacy is False:
  5357. event_pos = event.pos
  5358. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5359. # # Set the mouse button for panning
  5360. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5361. else:
  5362. event_pos = (event.xdata, event.ydata)
  5363. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5364. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5365. # So it can receive key presses
  5366. self.plotcanvas.native.setFocus()
  5367. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5368. if self.grid_status():
  5369. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5370. else:
  5371. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5372. try:
  5373. if event.button == 1:
  5374. # Reset here the relative coordinates so there is a new reference on the click position
  5375. if self.rel_point1 is None:
  5376. self.rel_point1 = self.pos
  5377. else:
  5378. self.rel_point2 = copy(self.rel_point1)
  5379. self.rel_point1 = self.pos
  5380. self.on_mouse_move_over_plot(event, origin_click=True)
  5381. except Exception as e:
  5382. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5383. def on_mouse_double_click_over_plot(self, event):
  5384. if event.button == 1:
  5385. self.doubleclick = True
  5386. def on_mouse_move_over_plot(self, event, origin_click=None):
  5387. """
  5388. Callback for the mouse motion event over the plot.
  5389. :param event: Contains information about the event.
  5390. :param origin_click
  5391. :return: None
  5392. """
  5393. if self.is_legacy is False:
  5394. event_pos = event.pos
  5395. if self.defaults["global_pan_button"] == '2':
  5396. pan_button = 2
  5397. else:
  5398. pan_button = 3
  5399. self.event_is_dragging = event.is_dragging
  5400. else:
  5401. event_pos = (event.xdata, event.ydata)
  5402. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5403. if self.defaults["global_pan_button"] == '2':
  5404. pan_button = 3
  5405. else:
  5406. pan_button = 2
  5407. self.event_is_dragging = self.plotcanvas.is_dragging
  5408. # So it can receive key presses but not when the Tcl Shell is active
  5409. if not self.ui.shell_dock.isVisible():
  5410. if not self.plotcanvas.native.hasFocus():
  5411. self.plotcanvas.native.setFocus()
  5412. self.pos_jump = event_pos
  5413. self.ui.popMenu.mouse_is_panning = False
  5414. if origin_click is None:
  5415. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5416. if event.button == pan_button and self.event_is_dragging == 1:
  5417. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5418. if self.ui.popMenu.popup_active:
  5419. self.ui.popMenu.popup_active = False
  5420. return
  5421. self.ui.popMenu.mouse_is_panning = True
  5422. return
  5423. if self.rel_point1 is not None:
  5424. try: # May fail in case mouse not within axes
  5425. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5426. if pos_canvas[0] is None or pos_canvas[1] is None:
  5427. return
  5428. if self.grid_status():
  5429. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5430. # Update cursor
  5431. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5432. symbol='++', edge_color=self.cursor_color_3D,
  5433. edge_width=self.defaults["global_cursor_width"],
  5434. size=self.defaults["global_cursor_size"])
  5435. else:
  5436. pos = (pos_canvas[0], pos_canvas[1])
  5437. self.dx = pos[0] - float(self.rel_point1[0])
  5438. self.dy = pos[1] - float(self.rel_point1[1])
  5439. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5440. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  5441. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5442. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5443. units = self.defaults["units"].lower()
  5444. self.plotcanvas.text_hud.text = \
  5445. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  5446. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  5447. self.mouse = [pos[0], pos[1]]
  5448. # if the mouse is moved and the LMB is clicked then the action is a selection
  5449. if self.event_is_dragging == 1 and event.button == 1:
  5450. self.delete_selection_shape()
  5451. if self.dx < 0:
  5452. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5453. face_color=self.defaults['global_alt_sel_fill'])
  5454. self.selection_type = False
  5455. elif self.dx >= 0:
  5456. self.draw_moving_selection_shape(self.pos, pos)
  5457. self.selection_type = True
  5458. else:
  5459. self.selection_type = None
  5460. else:
  5461. self.selection_type = None
  5462. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  5463. if self.defaults['global_hover']:
  5464. for obj in self.collection.get_list():
  5465. try:
  5466. # select the object(s) only if it is enabled (plotted)
  5467. if obj.options['plot']:
  5468. if obj not in self.collection.get_selected():
  5469. poly_obj = Polygon(
  5470. [(obj.options['xmin'], obj.options['ymin']),
  5471. (obj.options['xmax'], obj.options['ymin']),
  5472. (obj.options['xmax'], obj.options['ymax']),
  5473. (obj.options['xmin'], obj.options['ymax'])]
  5474. )
  5475. if Point(pos).within(poly_obj):
  5476. if obj.isHovering is False:
  5477. obj.isHovering = True
  5478. obj.notHovering = True
  5479. # create the selection box around the selected object
  5480. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5481. else:
  5482. if obj.notHovering is True:
  5483. obj.notHovering = False
  5484. obj.isHovering = False
  5485. self.delete_hover_shape()
  5486. except Exception:
  5487. # the Exception here will happen if we try to select on screen and we have an
  5488. # newly (and empty) just created Geometry or Excellon object that do not have the
  5489. # xmin, xmax, ymin, ymax options.
  5490. # In this case poly_obj creation (see above) will fail
  5491. pass
  5492. except Exception as e:
  5493. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5494. self.ui.position_label.setText("")
  5495. # self.ui.rel_position_label.setText("")
  5496. self.mouse = None
  5497. def on_mouse_click_release_over_plot(self, event):
  5498. """
  5499. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5500. and has been registered in ''self.__init__()''.
  5501. :param event: contains information about the event.
  5502. :return:
  5503. """
  5504. if self.is_legacy is False:
  5505. event_pos = event.pos
  5506. right_button = 2
  5507. else:
  5508. event_pos = (event.xdata, event.ydata)
  5509. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5510. right_button = 3
  5511. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5512. if self.grid_status():
  5513. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5514. else:
  5515. pos = (pos_canvas[0], pos_canvas[1])
  5516. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5517. # canvas menu
  5518. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5519. self.ui.popMenu.mouse_is_panning = False
  5520. self.cursor = QtGui.QCursor()
  5521. self.populate_cmenu_grids()
  5522. self.ui.popMenu.popup(self.cursor.pos())
  5523. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5524. # selection and then select a type of selection ("enclosing" or "touching")
  5525. if event.button == 1: # left click
  5526. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5527. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5528. if modifiers == QtCore.Qt.ShiftModifier:
  5529. # do not auto open the Project Tab
  5530. self.click_noproject = True
  5531. self.clipboard.setText(
  5532. self.defaults["global_point_clipboard_format"] %
  5533. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5534. )
  5535. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5536. return
  5537. if self.doubleclick is True:
  5538. self.doubleclick = False
  5539. if self.collection.get_selected():
  5540. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5541. if self.ui.splitter.sizes()[0] == 0:
  5542. self.ui.splitter.setSizes([1, 1])
  5543. try:
  5544. # delete the selection shape(S) as it may be in the way
  5545. self.delete_selection_shape()
  5546. self.delete_hover_shape()
  5547. except Exception as e:
  5548. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5549. return
  5550. else:
  5551. # WORKAROUND for LEGACY MODE
  5552. if self.is_legacy is True:
  5553. # if there is no move on canvas then we have no dragging selection
  5554. if self.dx == 0 or self.dy == 0:
  5555. self.selection_type = None
  5556. if self.selection_type is not None:
  5557. try:
  5558. self.selection_area_handler(self.pos, pos, self.selection_type)
  5559. self.selection_type = None
  5560. except Exception as e:
  5561. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5562. return
  5563. else:
  5564. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5565. if key_modifier == QtCore.Qt.ShiftModifier:
  5566. mod_key = 'Shift'
  5567. elif key_modifier == QtCore.Qt.ControlModifier:
  5568. mod_key = 'Control'
  5569. else:
  5570. mod_key = None
  5571. try:
  5572. if self.command_active is None:
  5573. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5574. # deselect, and if it's not selected then it will be selected
  5575. # If there is no active command (self.command_active is None) then we check if we clicked
  5576. # on a object by checking the bounding limits against mouse click position
  5577. if mod_key == self.defaults["global_mselect_key"]:
  5578. self.select_objects(key='multisel')
  5579. else:
  5580. # If there is no active command (self.command_active is None) then we check if
  5581. # we clicked on a object by checking the bounding limits against mouse click position
  5582. self.select_objects()
  5583. self.delete_hover_shape()
  5584. except Exception as e:
  5585. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5586. return
  5587. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5588. """
  5589. :param start_pos: mouse position when the selection LMB click was done
  5590. :param end_pos: mouse position when the left mouse button is released
  5591. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5592. :return:
  5593. """
  5594. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5595. # delete previous selection shape
  5596. self.delete_selection_shape()
  5597. # make all objects inactive
  5598. self.collection.set_all_inactive()
  5599. for obj in self.collection.get_list():
  5600. try:
  5601. # select the object(s) only if it is enabled (plotted)
  5602. if obj.options['plot']:
  5603. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5604. (obj.options['xmax'], obj.options['ymin']),
  5605. (obj.options['xmax'], obj.options['ymax']),
  5606. (obj.options['xmin'], obj.options['ymax'])])
  5607. if sel_type is True:
  5608. if poly_obj.within(poly_selection):
  5609. # create the selection box around the selected object
  5610. if self.defaults['global_selection_shape'] is True:
  5611. self.draw_selection_shape(obj)
  5612. self.collection.set_active(obj.options['name'])
  5613. else:
  5614. if poly_selection.intersects(poly_obj):
  5615. # create the selection box around the selected object
  5616. if self.defaults['global_selection_shape'] is True:
  5617. self.draw_selection_shape(obj)
  5618. self.collection.set_active(obj.options['name'])
  5619. obj.selection_shape_drawn = True
  5620. except Exception as e:
  5621. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5622. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5623. # In this case poly_obj creation (see above) will fail
  5624. log.debug("App.selection_area_handler() --> %s" % str(e))
  5625. def select_objects(self, key=None):
  5626. """
  5627. Will select objects clicked on canvas
  5628. :param key: for future use in cumulative selection
  5629. :return:
  5630. """
  5631. # list where we store the overlapped objects under our mouse left click position
  5632. if key is None:
  5633. self.objects_under_the_click_list = []
  5634. # Populate the list with the overlapped objects on the click position
  5635. curr_x, curr_y = self.pos
  5636. for obj in self.all_objects_list:
  5637. # ScriptObject and DocumentObject objects can't be selected
  5638. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5639. continue
  5640. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5641. continue
  5642. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5643. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5644. if obj.options['name'] not in self.objects_under_the_click_list:
  5645. if obj.options['plot']:
  5646. # add objects to the objects_under_the_click list only if the object is plotted
  5647. # (active and not disabled)
  5648. self.objects_under_the_click_list.append(obj.options['name'])
  5649. try:
  5650. if self.objects_under_the_click_list:
  5651. curr_sel_obj = self.collection.get_active()
  5652. # case when there is only an object under the click and we toggle it
  5653. if len(self.objects_under_the_click_list) == 1:
  5654. if curr_sel_obj is None:
  5655. self.collection.set_active(self.objects_under_the_click_list[0])
  5656. curr_sel_obj = self.collection.get_active()
  5657. # create the selection box around the selected object
  5658. if self.defaults['global_selection_shape'] is True:
  5659. self.draw_selection_shape(curr_sel_obj)
  5660. curr_sel_obj.selection_shape_drawn = True
  5661. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5662. self.on_objects_selection(False)
  5663. self.delete_selection_shape()
  5664. curr_sel_obj.selection_shape_drawn = False
  5665. self.collection.set_active(self.objects_under_the_click_list[0])
  5666. curr_sel_obj = self.collection.get_active()
  5667. # create the selection box around the selected object
  5668. if self.defaults['global_selection_shape'] is True:
  5669. self.draw_selection_shape(curr_sel_obj)
  5670. curr_sel_obj.selection_shape_drawn = True
  5671. self.selected_message(curr_sel_obj=curr_sel_obj)
  5672. elif curr_sel_obj.selection_shape_drawn is False:
  5673. if self.defaults['global_selection_shape'] is True:
  5674. self.draw_selection_shape(curr_sel_obj)
  5675. curr_sel_obj.selection_shape_drawn = True
  5676. else:
  5677. self.on_objects_selection(False)
  5678. self.delete_selection_shape()
  5679. if self.call_source != 'app':
  5680. self.call_source = 'app'
  5681. self.selected_message(curr_sel_obj=curr_sel_obj)
  5682. else:
  5683. # If there is no selected object
  5684. # make active the first element of the overlapped objects list
  5685. if self.collection.get_active() is None:
  5686. self.collection.set_active(self.objects_under_the_click_list[0])
  5687. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5688. name_sel_obj = self.collection.get_active().options['name']
  5689. # In case that there is a selected object but it is not in the overlapped object list
  5690. # make that object inactive and activate the first element in the overlapped object list
  5691. if name_sel_obj not in self.objects_under_the_click_list:
  5692. self.collection.set_inactive(name_sel_obj)
  5693. name_sel_obj = self.objects_under_the_click_list[0]
  5694. self.collection.set_active(name_sel_obj)
  5695. else:
  5696. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5697. self.collection.set_all_inactive()
  5698. self.collection.set_active(
  5699. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5700. curr_sel_obj = self.collection.get_active()
  5701. # delete the possible selection box around a possible selected object
  5702. self.delete_selection_shape()
  5703. curr_sel_obj.selection_shape_drawn = False
  5704. # create the selection box around the selected object
  5705. if self.defaults['global_selection_shape'] is True:
  5706. self.draw_selection_shape(curr_sel_obj)
  5707. curr_sel_obj.selection_shape_drawn = True
  5708. self.selected_message(curr_sel_obj=curr_sel_obj)
  5709. else:
  5710. # deselect everything
  5711. self.on_objects_selection(False)
  5712. # delete the possible selection box around a possible selected object
  5713. self.delete_selection_shape()
  5714. for o in self.collection.get_list():
  5715. o.selection_shape_drawn = False
  5716. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5717. # only when working on App
  5718. if self.call_source == 'app':
  5719. if self.click_noproject is False:
  5720. # if the Tool Tab is in focus don't change focus to Project Tab
  5721. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5722. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5723. else:
  5724. # restore auto open the Project Tab
  5725. self.click_noproject = False
  5726. # delete any text in the status bar, implicitly the last object name that was selected
  5727. # self.inform.emit("")
  5728. else:
  5729. self.call_source = 'app'
  5730. except Exception as e:
  5731. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5732. def selected_message(self, curr_sel_obj):
  5733. if curr_sel_obj:
  5734. if curr_sel_obj.kind == 'gerber':
  5735. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5736. color='green',
  5737. name=str(curr_sel_obj.options['name']),
  5738. tx=_("selected"))
  5739. )
  5740. elif curr_sel_obj.kind == 'excellon':
  5741. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5742. color='brown',
  5743. name=str(curr_sel_obj.options['name']),
  5744. tx=_("selected"))
  5745. )
  5746. elif curr_sel_obj.kind == 'cncjob':
  5747. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5748. color='blue',
  5749. name=str(curr_sel_obj.options['name']),
  5750. tx=_("selected"))
  5751. )
  5752. elif curr_sel_obj.kind == 'geometry':
  5753. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5754. color='red',
  5755. name=str(curr_sel_obj.options['name']),
  5756. tx=_("selected"))
  5757. )
  5758. def delete_hover_shape(self):
  5759. self.hover_shapes.clear()
  5760. self.hover_shapes.redraw()
  5761. def draw_hover_shape(self, sel_obj, color=None):
  5762. """
  5763. :param sel_obj: The object for which the hover shape must be drawn
  5764. :param color: The color of the hover shape
  5765. :return: None
  5766. """
  5767. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5768. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5769. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5770. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5771. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5772. if self.defaults['units'].upper() == 'MM':
  5773. hover_rect = hover_rect.buffer(-0.1)
  5774. hover_rect = hover_rect.buffer(0.2)
  5775. else:
  5776. hover_rect = hover_rect.buffer(-0.00393)
  5777. hover_rect = hover_rect.buffer(0.00787)
  5778. # if color:
  5779. # face = Color(color)
  5780. # face.alpha = 0.2
  5781. # outline = Color(color, alpha=0.8)
  5782. # else:
  5783. # face = Color(self.defaults['global_sel_fill'])
  5784. # face.alpha = 0.2
  5785. # outline = self.defaults['global_sel_line']
  5786. if color:
  5787. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5788. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5789. else:
  5790. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5791. outline = self.defaults['global_sel_line']
  5792. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5793. if self.is_legacy is True:
  5794. self.hover_shapes.redraw()
  5795. def delete_selection_shape(self):
  5796. self.move_tool.sel_shapes.clear()
  5797. self.move_tool.sel_shapes.redraw()
  5798. def draw_selection_shape(self, sel_obj, color=None):
  5799. """
  5800. Will draw a selection shape around the selected object.
  5801. :param sel_obj: The object for which the selection shape must be drawn
  5802. :param color: The color for the selection shape.
  5803. :return: None
  5804. """
  5805. if sel_obj is None:
  5806. return
  5807. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5808. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5809. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5810. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5811. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5812. if self.defaults['units'].upper() == 'MM':
  5813. sel_rect = sel_rect.buffer(-0.1)
  5814. sel_rect = sel_rect.buffer(0.2)
  5815. else:
  5816. sel_rect = sel_rect.buffer(-0.00393)
  5817. sel_rect = sel_rect.buffer(0.00787)
  5818. if color:
  5819. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5820. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5821. else:
  5822. if self.is_legacy is False:
  5823. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5824. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5825. else:
  5826. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5827. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5828. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5829. color=outline,
  5830. face_color=face,
  5831. update=True,
  5832. layer=0,
  5833. tolerance=None))
  5834. if self.is_legacy is True:
  5835. self.move_tool.sel_shapes.redraw()
  5836. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5837. """
  5838. Will draw a selection shape when dragging mouse on canvas.
  5839. :param old_coords: Old coordinates
  5840. :param coords: New coordinates
  5841. :param kwargs: Keyword arguments
  5842. :return:
  5843. """
  5844. if 'color' in kwargs:
  5845. color = kwargs['color']
  5846. else:
  5847. color = self.defaults['global_sel_line']
  5848. if 'face_color' in kwargs:
  5849. face_color = kwargs['face_color']
  5850. else:
  5851. face_color = self.defaults['global_sel_fill']
  5852. if 'face_alpha' in kwargs:
  5853. face_alpha = kwargs['face_alpha']
  5854. else:
  5855. face_alpha = 0.3
  5856. x0, y0 = old_coords
  5857. x1, y1 = coords
  5858. pt1 = (x0, y0)
  5859. pt2 = (x1, y0)
  5860. pt3 = (x1, y1)
  5861. pt4 = (x0, y1)
  5862. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5863. # color_t = Color(face_color)
  5864. # color_t.alpha = face_alpha
  5865. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5866. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5867. layer=0, tolerance=None)
  5868. if self.is_legacy is True:
  5869. self.move_tool.sel_shapes.redraw()
  5870. def on_file_new_click(self):
  5871. """
  5872. Callback for menu item File -> New.
  5873. Executed on clicking the Menu -> File -> New Project
  5874. :return:
  5875. """
  5876. if self.collection.get_list() and self.should_we_save:
  5877. msgbox = QtWidgets.QMessageBox()
  5878. # msgbox.setText("<B>Save changes ...</B>")
  5879. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5880. "Creating a New project will delete them.\n"
  5881. "Do you want to Save the project?"))
  5882. msgbox.setWindowTitle(_("Save changes"))
  5883. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5884. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5885. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5886. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5887. msgbox.setDefaultButton(bt_yes)
  5888. msgbox.exec_()
  5889. response = msgbox.clickedButton()
  5890. if response == bt_yes:
  5891. self.on_file_saveprojectas()
  5892. elif response == bt_cancel:
  5893. return
  5894. elif response == bt_no:
  5895. self.on_file_new()
  5896. else:
  5897. self.on_file_new()
  5898. self.inform.emit('[success] %s...' % _("New Project created"))
  5899. def on_file_new(self, cli=None):
  5900. """
  5901. Returns the application to its startup state. This method is thread-safe.
  5902. :param cli: Boolean. If True this method was run from command line
  5903. :return: None
  5904. """
  5905. self.defaults.report_usage("on_file_new")
  5906. # Remove everything from memory
  5907. App.log.debug("on_file_new()")
  5908. # close any editor that might be open
  5909. if self.call_source != 'app':
  5910. self.editor2object(cleanup=True)
  5911. # ## EDITOR section
  5912. self.geo_editor = FlatCAMGeoEditor(self)
  5913. self.exc_editor = FlatCAMExcEditor(self)
  5914. self.grb_editor = FlatCAMGrbEditor(self)
  5915. # Clear pool
  5916. self.clear_pool()
  5917. for obj in self.collection.get_list():
  5918. # delete shapes left drawn from mark shape_collections, if any
  5919. if isinstance(obj, GerberObject):
  5920. try:
  5921. for el in obj.mark_shapes:
  5922. obj.mark_shapes[el].clear(update=True)
  5923. obj.mark_shapes[el].enabled = False
  5924. del el
  5925. except AttributeError:
  5926. pass
  5927. # also delete annotation shapes, if any
  5928. elif isinstance(obj, CNCJobObject):
  5929. try:
  5930. obj.text_col.enabled = False
  5931. del obj.text_col
  5932. obj.annotation.clear(update=True)
  5933. del obj.annotation
  5934. except AttributeError:
  5935. pass
  5936. # delete the exclusion areas
  5937. self.exc_areas.clear_shapes()
  5938. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5939. self.shell.init_tcl()
  5940. # delete any selection shape on canvas
  5941. self.delete_selection_shape()
  5942. # delete all FlatCAM objects
  5943. self.collection.delete_all()
  5944. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5945. self.setup_component_editor()
  5946. # Clear project filename
  5947. self.project_filename = None
  5948. # Load the application defaults
  5949. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5950. # Re-fresh project options
  5951. self.on_options_app2project()
  5952. # Init FlatCAMTools
  5953. self.init_tools()
  5954. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5955. if cli is None:
  5956. # we need to go in reverse because once we remove a tab then the index changes
  5957. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5958. # and so on. Therefore the deletion should be done in reverse
  5959. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5960. for index in range(wdg_count, -1, -1):
  5961. try:
  5962. self.ui.plot_tab_area.closeTab(index)
  5963. except Exception as e:
  5964. log.debug("App.on_file_new() --> %s" % str(e))
  5965. # # And then add again the Plot Area
  5966. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5967. self.ui.plot_tab_area.protectTab(0)
  5968. # take the focus of the Notebook on Project Tab.
  5969. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5970. self.set_ui_title(name=_("New Project - Not saved"))
  5971. def obj_properties(self):
  5972. """
  5973. Will launch the object Properties Tool
  5974. :return:
  5975. """
  5976. self.defaults.report_usage("obj_properties()")
  5977. self.properties_tool.run(toggle=False)
  5978. def on_project_context_save(self):
  5979. """
  5980. Wrapper, will save the object function of it's type
  5981. :return:
  5982. """
  5983. obj = self.collection.get_active()
  5984. if type(obj) == GeometryObject:
  5985. self.on_file_exportdxf()
  5986. elif type(obj) == ExcellonObject:
  5987. self.on_file_saveexcellon()
  5988. elif type(obj) == CNCJobObject:
  5989. obj.on_exportgcode_button_click()
  5990. elif type(obj) == GerberObject:
  5991. self.on_file_savegerber()
  5992. elif type(obj) == ScriptObject:
  5993. self.on_file_savescript()
  5994. elif type(obj) == DocumentObject:
  5995. self.on_file_savedocument()
  5996. def obj_move(self):
  5997. """
  5998. Callback for the Move menu entry in various Context Menu's.
  5999. :return:
  6000. """
  6001. self.defaults.report_usage("obj_move()")
  6002. self.move_tool.run(toggle=False)
  6003. def on_fileopengerber(self, signal, name=None):
  6004. """
  6005. File menu callback for opening a Gerber.
  6006. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6007. :param name:
  6008. :return: None
  6009. """
  6010. self.defaults.report_usage("on_fileopengerber")
  6011. App.log.debug("on_fileopengerber()")
  6012. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6013. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6014. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6015. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6016. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6017. "*.mil);;" \
  6018. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6019. "Allegro Files (*.art);;" \
  6020. "Mentor Files (*.pho *.gdo);;" \
  6021. "All Files (*.*)"
  6022. if name is None:
  6023. try:
  6024. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6025. directory=self.get_last_folder(),
  6026. filter=_filter_)
  6027. except TypeError:
  6028. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6029. filenames = [str(filename) for filename in filenames]
  6030. else:
  6031. filenames = [name]
  6032. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6033. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6034. _("Opening Gerber file.")),
  6035. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6036. color=QtGui.QColor("gray"))
  6037. if len(filenames) == 0:
  6038. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6039. else:
  6040. for filename in filenames:
  6041. if filename != '':
  6042. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6043. def on_fileopenexcellon(self, signal, name=None):
  6044. """
  6045. File menu callback for opening an Excellon file.
  6046. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6047. :param name:
  6048. :return: None
  6049. """
  6050. self.defaults.report_usage("on_fileopenexcellon")
  6051. App.log.debug("on_fileopenexcellon()")
  6052. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6053. "All Files (*.*)"
  6054. if name is None:
  6055. try:
  6056. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6057. directory=self.get_last_folder(),
  6058. filter=_filter_)
  6059. except TypeError:
  6060. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6061. filenames = [str(filename) for filename in filenames]
  6062. else:
  6063. filenames = [str(name)]
  6064. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6065. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6066. _("Opening Excellon file.")),
  6067. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6068. color=QtGui.QColor("gray"))
  6069. if len(filenames) == 0:
  6070. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6071. else:
  6072. for filename in filenames:
  6073. if filename != '':
  6074. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6075. def on_fileopengcode(self, signal, name=None):
  6076. """
  6077. File menu call back for opening gcode.
  6078. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6079. :param name:
  6080. :return:
  6081. """
  6082. self.defaults.report_usage("on_fileopengcode")
  6083. App.log.debug("on_fileopengcode()")
  6084. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6085. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6086. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6087. "All Files (*.*)"
  6088. if name is None:
  6089. try:
  6090. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6091. directory=self.get_last_folder(),
  6092. filter=_filter_)
  6093. except TypeError:
  6094. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6095. filenames = [str(filename) for filename in filenames]
  6096. else:
  6097. filenames = [name]
  6098. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6099. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6100. _("Opening G-Code file.")),
  6101. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6102. color=QtGui.QColor("gray"))
  6103. if len(filenames) == 0:
  6104. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6105. else:
  6106. for filename in filenames:
  6107. if filename != '':
  6108. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6109. def on_file_openproject(self, signal):
  6110. """
  6111. File menu callback for opening a project.
  6112. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6113. :return: None
  6114. """
  6115. self.defaults.report_usage("on_file_openproject")
  6116. App.log.debug("on_file_openproject()")
  6117. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6118. try:
  6119. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6120. directory=self.get_last_folder(), filter=_filter_)
  6121. except TypeError:
  6122. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6123. # The Qt methods above will return a QString which can cause problems later.
  6124. # So far json.dump() will fail to serialize it.
  6125. # TODO: Improve the serialization methods and remove this fix.
  6126. filename = str(filename)
  6127. if filename == "":
  6128. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6129. else:
  6130. # self.worker_task.emit({'fcn': self.open_project,
  6131. # 'params': [filename]})
  6132. # The above was failing because open_project() is not
  6133. # thread safe. The new_project()
  6134. self.open_project(filename)
  6135. def on_fileopenhpgl2(self, signal, name=None):
  6136. """
  6137. File menu callback for opening a HPGL2.
  6138. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6139. :param name:
  6140. :return: None
  6141. """
  6142. self.defaults.report_usage("on_fileopenhpgl2")
  6143. App.log.debug("on_fileopenhpgl2()")
  6144. _filter_ = "HPGL2 Files (*.plt);;" \
  6145. "All Files (*.*)"
  6146. if name is None:
  6147. try:
  6148. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6149. directory=self.get_last_folder(),
  6150. filter=_filter_)
  6151. except TypeError:
  6152. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6153. filenames = [str(filename) for filename in filenames]
  6154. else:
  6155. filenames = [name]
  6156. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6157. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6158. _("Opening HPGL2 file.")),
  6159. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6160. color=QtGui.QColor("gray"))
  6161. if len(filenames) == 0:
  6162. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6163. else:
  6164. for filename in filenames:
  6165. if filename != '':
  6166. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6167. def on_file_openconfig(self, signal):
  6168. """
  6169. File menu callback for opening a config file.
  6170. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6171. :return: None
  6172. """
  6173. self.defaults.report_usage("on_file_openconfig")
  6174. App.log.debug("on_file_openconfig()")
  6175. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6176. try:
  6177. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6178. directory=self.data_path, filter=_filter_)
  6179. except TypeError:
  6180. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6181. filter=_filter_)
  6182. if filename == "":
  6183. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6184. else:
  6185. self.open_config_file(filename)
  6186. def on_file_exportsvg(self):
  6187. """
  6188. Callback for menu item File->Export SVG.
  6189. :return: None
  6190. """
  6191. self.defaults.report_usage("on_file_exportsvg")
  6192. App.log.debug("on_file_exportsvg()")
  6193. obj = self.collection.get_active()
  6194. if obj is None:
  6195. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6196. msg = _("Please Select a Geometry object to export")
  6197. msgbox = QtWidgets.QMessageBox()
  6198. msgbox.setInformativeText(msg)
  6199. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6200. msgbox.setDefaultButton(bt_ok)
  6201. msgbox.exec_()
  6202. return
  6203. # Check for more compatible types and add as required
  6204. if (not isinstance(obj, GeometryObject)
  6205. and not isinstance(obj, GerberObject)
  6206. and not isinstance(obj, CNCJobObject)
  6207. and not isinstance(obj, ExcellonObject)):
  6208. msg = '[ERROR_NOTCL] %s' % \
  6209. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6210. msgbox = QtWidgets.QMessageBox()
  6211. msgbox.setInformativeText(msg)
  6212. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6213. msgbox.setDefaultButton(bt_ok)
  6214. msgbox.exec_()
  6215. return
  6216. name = obj.options["name"]
  6217. _filter = "SVG File (*.svg);;All Files (*.*)"
  6218. try:
  6219. filename, _f = FCFileSaveDialog.get_saved_filename(
  6220. caption=_("Export SVG"),
  6221. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6222. filter=_filter)
  6223. except TypeError:
  6224. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6225. filename = str(filename)
  6226. if filename == "":
  6227. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6228. return
  6229. else:
  6230. self.export_svg(name, filename)
  6231. if self.defaults["global_open_style"] is False:
  6232. self.file_opened.emit("SVG", filename)
  6233. self.file_saved.emit("SVG", filename)
  6234. def on_file_exportpng(self):
  6235. self.defaults.report_usage("on_file_exportpng")
  6236. App.log.debug("on_file_exportpng()")
  6237. self.date = str(datetime.today()).rpartition('.')[0]
  6238. self.date = ''.join(c for c in self.date if c not in ':-')
  6239. self.date = self.date.replace(' ', '_')
  6240. if self.is_legacy is False:
  6241. image = _screenshot()
  6242. data = np.asarray(image)
  6243. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6244. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6245. return
  6246. filter_ = "PNG File (*.png);;All Files (*.*)"
  6247. try:
  6248. filename, _f = FCFileSaveDialog.get_saved_filename(
  6249. caption=_("Export PNG Image"),
  6250. directory=self.get_last_save_folder() + '/png_' + self.date,
  6251. filter=filter_)
  6252. except TypeError:
  6253. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6254. filename = str(filename)
  6255. if filename == "":
  6256. self.inform.emit(_("Cancelled."))
  6257. return
  6258. else:
  6259. if self.is_legacy is False:
  6260. write_png(filename, data)
  6261. else:
  6262. self.plotcanvas.figure.savefig(filename)
  6263. if self.defaults["global_open_style"] is False:
  6264. self.file_opened.emit("png", filename)
  6265. self.file_saved.emit("png", filename)
  6266. def on_file_savegerber(self):
  6267. """
  6268. Callback for menu item in Project context menu.
  6269. :return: None
  6270. """
  6271. self.defaults.report_usage("on_file_savegerber")
  6272. App.log.debug("on_file_savegerber()")
  6273. obj = self.collection.get_active()
  6274. if obj is None:
  6275. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6276. return
  6277. # Check for more compatible types and add as required
  6278. if not isinstance(obj, GerberObject):
  6279. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6280. return
  6281. name = self.collection.get_active().options["name"]
  6282. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6283. try:
  6284. filename, _f = FCFileSaveDialog.get_saved_filename(
  6285. caption="Save Gerber source file",
  6286. directory=self.get_last_save_folder() + '/' + name,
  6287. filter=_filter)
  6288. except TypeError:
  6289. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6290. filename = str(filename)
  6291. if filename == "":
  6292. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6293. return
  6294. else:
  6295. self.save_source_file(name, filename)
  6296. if self.defaults["global_open_style"] is False:
  6297. self.file_opened.emit("Gerber", filename)
  6298. self.file_saved.emit("Gerber", filename)
  6299. def on_file_savescript(self):
  6300. """
  6301. Callback for menu item in Project context menu.
  6302. :return: None
  6303. """
  6304. self.defaults.report_usage("on_file_savescript")
  6305. App.log.debug("on_file_savescript()")
  6306. obj = self.collection.get_active()
  6307. if obj is None:
  6308. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6309. return
  6310. # Check for more compatible types and add as required
  6311. if not isinstance(obj, ScriptObject):
  6312. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6313. return
  6314. name = self.collection.get_active().options["name"]
  6315. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6316. try:
  6317. filename, _f = FCFileSaveDialog.get_saved_filename(
  6318. caption="Save Script source file",
  6319. directory=self.get_last_save_folder() + '/' + name,
  6320. filter=_filter)
  6321. except TypeError:
  6322. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6323. filename = str(filename)
  6324. if filename == "":
  6325. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6326. return
  6327. else:
  6328. self.save_source_file(name, filename)
  6329. if self.defaults["global_open_style"] is False:
  6330. self.file_opened.emit("Script", filename)
  6331. self.file_saved.emit("Script", filename)
  6332. def on_file_savedocument(self):
  6333. """
  6334. Callback for menu item in Project context menu.
  6335. :return: None
  6336. """
  6337. self.defaults.report_usage("on_file_savedocument")
  6338. App.log.debug("on_file_savedocument()")
  6339. obj = self.collection.get_active()
  6340. if obj is None:
  6341. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6342. return
  6343. # Check for more compatible types and add as required
  6344. if not isinstance(obj, ScriptObject):
  6345. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6346. return
  6347. name = self.collection.get_active().options["name"]
  6348. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6349. try:
  6350. filename, _f = FCFileSaveDialog.get_saved_filename(
  6351. caption="Save Document source file",
  6352. directory=self.get_last_save_folder() + '/' + name,
  6353. filter=_filter)
  6354. except TypeError:
  6355. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6356. filename = str(filename)
  6357. if filename == "":
  6358. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6359. return
  6360. else:
  6361. self.save_source_file(name, filename)
  6362. if self.defaults["global_open_style"] is False:
  6363. self.file_opened.emit("Document", filename)
  6364. self.file_saved.emit("Document", filename)
  6365. def on_file_saveexcellon(self):
  6366. """
  6367. Callback for menu item in project context menu.
  6368. :return: None
  6369. """
  6370. self.defaults.report_usage("on_file_saveexcellon")
  6371. App.log.debug("on_file_saveexcellon()")
  6372. obj = self.collection.get_active()
  6373. if obj is None:
  6374. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6375. return
  6376. # Check for more compatible types and add as required
  6377. if not isinstance(obj, ExcellonObject):
  6378. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6379. return
  6380. name = self.collection.get_active().options["name"]
  6381. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6382. try:
  6383. filename, _f = FCFileSaveDialog.get_saved_filename(
  6384. caption=_("Save Excellon source file"),
  6385. directory=self.get_last_save_folder() + '/' + name,
  6386. filter=_filter)
  6387. except TypeError:
  6388. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6389. filename = str(filename)
  6390. if filename == "":
  6391. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6392. return
  6393. else:
  6394. self.save_source_file(name, filename)
  6395. if self.defaults["global_open_style"] is False:
  6396. self.file_opened.emit("Excellon", filename)
  6397. self.file_saved.emit("Excellon", filename)
  6398. def on_file_exportexcellon(self):
  6399. """
  6400. Callback for menu item File->Export->Excellon.
  6401. :return: None
  6402. """
  6403. self.defaults.report_usage("on_file_exportexcellon")
  6404. App.log.debug("on_file_exportexcellon()")
  6405. obj = self.collection.get_active()
  6406. if obj is None:
  6407. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6408. return
  6409. # Check for more compatible types and add as required
  6410. if not isinstance(obj, ExcellonObject):
  6411. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6412. return
  6413. name = self.collection.get_active().options["name"]
  6414. _filter = self.defaults["excellon_save_filters"]
  6415. try:
  6416. filename, _f = FCFileSaveDialog.get_saved_filename(
  6417. caption=_("Export Excellon"),
  6418. directory=self.get_last_save_folder() + '/' + name,
  6419. filter=_filter)
  6420. except TypeError:
  6421. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6422. filename = str(filename)
  6423. if filename == "":
  6424. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6425. return
  6426. else:
  6427. used_extension = filename.rpartition('.')[2]
  6428. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6429. self.export_excellon(name, filename)
  6430. if self.defaults["global_open_style"] is False:
  6431. self.file_opened.emit("Excellon", filename)
  6432. self.file_saved.emit("Excellon", filename)
  6433. def on_file_exportgerber(self):
  6434. """
  6435. Callback for menu item File->Export->Gerber.
  6436. :return: None
  6437. """
  6438. self.defaults.report_usage("on_file_exportgerber")
  6439. App.log.debug("on_file_exportgerber()")
  6440. obj = self.collection.get_active()
  6441. if obj is None:
  6442. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6443. return
  6444. # Check for more compatible types and add as required
  6445. if not isinstance(obj, GerberObject):
  6446. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6447. return
  6448. name = self.collection.get_active().options["name"]
  6449. _filter_ = self.defaults['gerber_save_filters']
  6450. try:
  6451. filename, _f = FCFileSaveDialog.get_saved_filename(
  6452. caption=_("Export Gerber"),
  6453. directory=self.get_last_save_folder() + '/' + name,
  6454. filter=_filter_)
  6455. except TypeError:
  6456. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6457. filename = str(filename)
  6458. if filename == "":
  6459. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6460. return
  6461. else:
  6462. used_extension = filename.rpartition('.')[2]
  6463. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6464. self.export_gerber(name, filename)
  6465. if self.defaults["global_open_style"] is False:
  6466. self.file_opened.emit("Gerber", filename)
  6467. self.file_saved.emit("Gerber", filename)
  6468. def on_file_exportdxf(self):
  6469. """
  6470. Callback for menu item File->Export DXF.
  6471. :return: None
  6472. """
  6473. self.defaults.report_usage("on_file_exportdxf")
  6474. App.log.debug("on_file_exportdxf()")
  6475. obj = self.collection.get_active()
  6476. if obj is None:
  6477. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6478. msg = _("Please Select a Geometry object to export")
  6479. msgbox = QtWidgets.QMessageBox()
  6480. msgbox.setInformativeText(msg)
  6481. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6482. msgbox.setDefaultButton(bt_ok)
  6483. msgbox.exec_()
  6484. return
  6485. # Check for more compatible types and add as required
  6486. if not isinstance(obj, GeometryObject):
  6487. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6488. msgbox = QtWidgets.QMessageBox()
  6489. msgbox.setInformativeText(msg)
  6490. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6491. msgbox.setDefaultButton(bt_ok)
  6492. msgbox.exec_()
  6493. return
  6494. name = self.collection.get_active().options["name"]
  6495. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6496. try:
  6497. filename, _f = FCFileSaveDialog.get_saved_filename(
  6498. caption=_("Export DXF"),
  6499. directory=self.get_last_save_folder() + '/' + name,
  6500. filter=_filter_)
  6501. except TypeError:
  6502. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6503. filename = str(filename)
  6504. if filename == "":
  6505. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6506. return
  6507. else:
  6508. self.export_dxf(name, filename)
  6509. if self.defaults["global_open_style"] is False:
  6510. self.file_opened.emit("DXF", filename)
  6511. self.file_saved.emit("DXF", filename)
  6512. def on_file_importsvg(self, type_of_obj):
  6513. """
  6514. Callback for menu item File->Import SVG.
  6515. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6516. :type type_of_obj: str
  6517. :return: None
  6518. """
  6519. self.defaults.report_usage("on_file_importsvg")
  6520. App.log.debug("on_file_importsvg()")
  6521. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6522. try:
  6523. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6524. directory=self.get_last_folder(), filter=_filter_)
  6525. except TypeError:
  6526. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6527. filter=_filter_)
  6528. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6529. type_of_obj = "geometry"
  6530. filenames = [str(filename) for filename in filenames]
  6531. if len(filenames) == 0:
  6532. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6533. else:
  6534. for filename in filenames:
  6535. if filename != '':
  6536. self.worker_task.emit({'fcn': self.import_svg,
  6537. 'params': [filename, type_of_obj]})
  6538. def on_file_importdxf(self, type_of_obj):
  6539. """
  6540. Callback for menu item File->Import DXF.
  6541. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6542. :type type_of_obj: str
  6543. :return: None
  6544. """
  6545. self.defaults.report_usage("on_file_importdxf")
  6546. App.log.debug("on_file_importdxf()")
  6547. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6548. try:
  6549. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6550. directory=self.get_last_folder(),
  6551. filter=_filter_)
  6552. except TypeError:
  6553. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6554. filter=_filter_)
  6555. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6556. type_of_obj = "geometry"
  6557. filenames = [str(filename) for filename in filenames]
  6558. if len(filenames) == 0:
  6559. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6560. else:
  6561. for filename in filenames:
  6562. if filename != '':
  6563. self.worker_task.emit({'fcn': self.import_dxf,
  6564. 'params': [filename, type_of_obj]})
  6565. # ###############################################################################################################
  6566. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6567. # ###############################################################################################################
  6568. def init_code_editor(self, name):
  6569. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6570. # add the tab if it was closed
  6571. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6572. self.text_editor_tab.setObjectName('text_editor_tab')
  6573. # delete the absolute and relative position and messages in the infobar
  6574. self.ui.position_label.setText("")
  6575. # self.ui.rel_position_label.setText("")
  6576. # first clear previous text in text editor (if any)
  6577. self.text_editor_tab.code_editor.clear()
  6578. self.text_editor_tab.code_editor.setReadOnly(False)
  6579. self.toggle_codeeditor = True
  6580. self.text_editor_tab.code_editor.completer_enable = False
  6581. self.text_editor_tab.buttonRun.hide()
  6582. # make sure to keep a reference to the code editor
  6583. self.reference_code_editor = self.text_editor_tab.code_editor
  6584. # Switch plot_area to CNCJob tab
  6585. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6586. def on_view_source(self):
  6587. """
  6588. Called when the user wants to see the source file of the selected object
  6589. :return:
  6590. """
  6591. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6592. self.proc_container.view.set_busy(_("Loading..."))
  6593. try:
  6594. obj = self.collection.get_active()
  6595. except Exception as e:
  6596. log.debug("App.on_view_source() --> %s" % str(e))
  6597. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6598. return 'fail'
  6599. if obj is None:
  6600. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6601. return 'fail'
  6602. flt = "All Files (*.*)"
  6603. if obj.kind == 'gerber':
  6604. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6605. elif obj.kind == 'excellon':
  6606. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6607. elif obj.kind == 'cncjob':
  6608. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6609. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6610. # add the tab if it was closed
  6611. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6612. self.source_editor_tab.setObjectName('source_editor_tab')
  6613. # delete the absolute and relative position and messages in the infobar
  6614. self.ui.position_label.setText("")
  6615. # self.ui.rel_position_label.setText("")
  6616. # first clear previous text in text editor (if any)
  6617. self.source_editor_tab.code_editor.clear()
  6618. self.source_editor_tab.code_editor.setReadOnly(False)
  6619. self.source_editor_tab.code_editor.completer_enable = False
  6620. self.source_editor_tab.buttonRun.hide()
  6621. # Switch plot_area to CNCJob tab
  6622. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6623. try:
  6624. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6625. except TypeError:
  6626. pass
  6627. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6628. try:
  6629. self.source_editor_tab.buttonSave.clicked.disconnect()
  6630. except TypeError:
  6631. pass
  6632. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6633. # then append the text from GCode to the text editor
  6634. if obj.kind == 'cncjob':
  6635. try:
  6636. file = obj.export_gcode(
  6637. preamble=self.defaults["cncjob_prepend"],
  6638. postamble=self.defaults["cncjob_append"],
  6639. to_file=True)
  6640. if file == 'fail':
  6641. return 'fail'
  6642. except AttributeError:
  6643. self.inform.emit('[WARNING_NOTCL] %s' %
  6644. _("There is no selected object for which to see it's source file code."))
  6645. return 'fail'
  6646. else:
  6647. try:
  6648. file = StringIO(obj.source_file)
  6649. except (AttributeError, TypeError):
  6650. self.inform.emit('[WARNING_NOTCL] %s' %
  6651. _("There is no selected object for which to see it's source file code."))
  6652. return 'fail'
  6653. self.source_editor_tab.t_frame.hide()
  6654. try:
  6655. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6656. # for line in file:
  6657. # QtWidgets.QApplication.processEvents()
  6658. # proc_line = str(line).strip('\n')
  6659. # self.source_editor_tab.code_editor.append(proc_line)
  6660. except Exception as e:
  6661. log.debug('App.on_view_source() -->%s' % str(e))
  6662. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6663. return
  6664. self.source_editor_tab.handleTextChanged()
  6665. self.source_editor_tab.t_frame.show()
  6666. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6667. self.proc_container.view.set_idle()
  6668. # self.ui.show()
  6669. def on_toggle_code_editor(self):
  6670. self.defaults.report_usage("on_toggle_code_editor()")
  6671. if self.toggle_codeeditor is False:
  6672. self.init_code_editor(name=_("Code Editor"))
  6673. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6674. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6675. self.text_editor_tab.buttonSave.clicked.disconnect()
  6676. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6677. else:
  6678. for idx in range(self.ui.plot_tab_area.count()):
  6679. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6680. self.ui.plot_tab_area.closeTab(idx)
  6681. break
  6682. self.toggle_codeeditor = False
  6683. def on_code_editor_close(self):
  6684. self.toggle_codeeditor = False
  6685. def goto_text_line(self):
  6686. """
  6687. Will scroll a text to the specified text line.
  6688. :return: None
  6689. """
  6690. dia_box = Dialog_box(title=_("Go to Line ..."),
  6691. label=_("Line:"),
  6692. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6693. initial_text='')
  6694. try:
  6695. line = int(dia_box.location) - 1
  6696. except (ValueError, TypeError):
  6697. line = 0
  6698. if dia_box.ok:
  6699. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6700. # at the top of the window
  6701. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6702. # get the document() of the TextEditor
  6703. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6704. # create a Text Cursor based on the searched line
  6705. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6706. # set cursor of the code editor with the cursor at the searcehd line
  6707. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6708. def on_filenewscript(self, silent=False):
  6709. """
  6710. Will create a new script file and open it in the Code Editor
  6711. :param silent: if True will not display status messages
  6712. :param name: if specified will be the name of the new script
  6713. :param text: pass a source file to the newly created script to be loaded in it
  6714. :return: None
  6715. """
  6716. if silent is False:
  6717. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6718. # delete the absolute and relative position and messages in the infobar
  6719. self.ui.position_label.setText("")
  6720. # self.ui.rel_position_label.setText("")
  6721. self.new_script_object()
  6722. # script_text = script_obj.source_file
  6723. #
  6724. # self.proc_container.view.set_busy(_("Loading..."))
  6725. # script_obj.script_editor_tab.t_frame.hide()
  6726. #
  6727. # script_obj.script_editor_tab.t_frame.show()
  6728. # self.proc_container.view.set_idle()
  6729. def on_fileopenscript(self, name=None, silent=False):
  6730. """
  6731. Will open a Tcl script file into the Code Editor
  6732. :param silent: if True will not display status messages
  6733. :param name: name of a Tcl script file to open
  6734. :return: None
  6735. """
  6736. self.defaults.report_usage("on_fileopenscript")
  6737. App.log.debug("on_fileopenscript()")
  6738. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6739. "All Files (*.*)"
  6740. if name:
  6741. filenames = [name]
  6742. else:
  6743. try:
  6744. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6745. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6746. except TypeError:
  6747. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6748. if len(filenames) == 0:
  6749. if silent is False:
  6750. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6751. else:
  6752. for filename in filenames:
  6753. if filename != '':
  6754. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6755. def on_fileopenscript_example(self, name=None, silent=False):
  6756. """
  6757. Will open a Tcl script file into the Code Editor
  6758. :param silent: if True will not display status messages
  6759. :param name: name of a Tcl script file to open
  6760. :return:
  6761. """
  6762. self.defaults.report_usage("on_fileopenscript_example")
  6763. log.debug("on_fileopenscript_example()")
  6764. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6765. "All Files (*.*)"
  6766. # test if the app was frozen and choose the path for the configuration file
  6767. if getattr(sys, "frozen", False) is True:
  6768. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6769. else:
  6770. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6771. if name:
  6772. filenames = [name]
  6773. else:
  6774. try:
  6775. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6776. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6777. except TypeError:
  6778. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6779. if len(filenames) == 0:
  6780. if silent is False:
  6781. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6782. else:
  6783. for filename in filenames:
  6784. if filename != '':
  6785. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6786. def on_filerunscript(self, name=None, silent=False):
  6787. """
  6788. File menu callback for loading and running a TCL script.
  6789. :param silent: if True will not display status messages
  6790. :param name: name of a Tcl script file to be run by FlatCAM
  6791. :return: None
  6792. """
  6793. self.defaults.report_usage("on_filerunscript")
  6794. App.log.debug("on_file_runscript()")
  6795. if name:
  6796. filename = name
  6797. if self.cmd_line_headless != 1:
  6798. self.splash.showMessage('%s: %ssec\n%s' %
  6799. (_("Canvas initialization started.\n"
  6800. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6801. _("Executing ScriptObject file.")
  6802. ),
  6803. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6804. color=QtGui.QColor("gray"))
  6805. else:
  6806. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6807. "All Files (*.*)"
  6808. try:
  6809. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6810. directory=self.get_last_folder(), filter=_filter_)
  6811. except TypeError:
  6812. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6813. # The Qt methods above will return a QString which can cause problems later.
  6814. # So far json.dump() will fail to serialize it.
  6815. filename = str(filename)
  6816. if filename == "":
  6817. if silent is False:
  6818. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6819. else:
  6820. if self.cmd_line_headless != 1:
  6821. if self.ui.shell_dock.isHidden():
  6822. self.ui.shell_dock.show()
  6823. try:
  6824. with open(filename, "r") as tcl_script:
  6825. cmd_line_shellfile_content = tcl_script.read()
  6826. if self.cmd_line_headless != 1:
  6827. self.shell.exec_command(cmd_line_shellfile_content)
  6828. else:
  6829. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6830. if silent is False:
  6831. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6832. except Exception as e:
  6833. log.debug("App.on_filerunscript() -> %s" % str(e))
  6834. sys.exit(2)
  6835. def on_file_saveproject(self, silent=False):
  6836. """
  6837. Callback for menu item File->Save Project. Saves the project to
  6838. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6839. if set to None. The project is saved by calling ``self.save_project()``.
  6840. :param silent: if True will not display status messages
  6841. :return: None
  6842. """
  6843. self.defaults.report_usage("on_file_saveproject")
  6844. if self.project_filename is None:
  6845. self.on_file_saveprojectas()
  6846. else:
  6847. self.worker_task.emit({'fcn': self.save_project,
  6848. 'params': [self.project_filename, silent]})
  6849. if self.defaults["global_open_style"] is False:
  6850. self.file_opened.emit("project", self.project_filename)
  6851. self.file_saved.emit("project", self.project_filename)
  6852. self.set_ui_title(name=self.project_filename)
  6853. self.should_we_save = False
  6854. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6855. """
  6856. Callback for menu item File->Save Project As... Opens a file
  6857. chooser and saves the project to the given file via
  6858. ``self.save_project()``.
  6859. :param make_copy if to be create a copy of the project; boolean
  6860. :param use_thread: if to be run in a separate thread; boolean
  6861. :param quit_action: if to be followed by quiting the application; boolean
  6862. :return: None
  6863. """
  6864. self.defaults.report_usage("on_file_saveprojectas")
  6865. self.date = str(datetime.today()).rpartition('.')[0]
  6866. self.date = ''.join(c for c in self.date if c not in ':-')
  6867. self.date = self.date.replace(' ', '_')
  6868. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6869. try:
  6870. filename, _f = FCFileSaveDialog.get_saved_filename(
  6871. caption=_("Save Project As ..."),
  6872. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6873. proj=_("Project")),
  6874. filter=filter_
  6875. )
  6876. except TypeError:
  6877. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6878. filename = str(filename)
  6879. if filename == '':
  6880. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6881. return
  6882. if use_thread is True:
  6883. self.worker_task.emit({'fcn': self.save_project,
  6884. 'params': [filename, quit_action]})
  6885. else:
  6886. self.save_project(filename, quit_action)
  6887. # self.save_project(filename)
  6888. if self.defaults["global_open_style"] is False:
  6889. self.file_opened.emit("project", filename)
  6890. self.file_saved.emit("project", filename)
  6891. if not make_copy:
  6892. self.project_filename = filename
  6893. self.set_ui_title(name=self.project_filename)
  6894. self.should_we_save = False
  6895. def on_file_save_objects_pdf(self, use_thread=True):
  6896. self.date = str(datetime.today()).rpartition('.')[0]
  6897. self.date = ''.join(c for c in self.date if c not in ':-')
  6898. self.date = self.date.replace(' ', '_')
  6899. try:
  6900. obj_selection = self.collection.get_selected()
  6901. if len(obj_selection) == 1:
  6902. obj_name = str(obj_selection[0].options['name'])
  6903. else:
  6904. obj_name = _("FlatCAM objects print")
  6905. except AttributeError as err:
  6906. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6907. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6908. return
  6909. if not obj_selection:
  6910. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6911. return
  6912. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6913. try:
  6914. filename, _f = FCFileSaveDialog.get_saved_filename(
  6915. caption=_("Save Object as PDF ..."),
  6916. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6917. obj_name=obj_name,
  6918. date=self.date),
  6919. filter=filter_
  6920. )
  6921. except TypeError:
  6922. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6923. filename = str(filename)
  6924. if filename == '':
  6925. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6926. return
  6927. if use_thread is True:
  6928. self.proc_container.new(_("Printing PDF ... Please wait."))
  6929. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6930. else:
  6931. self.save_pdf(filename, obj_selection)
  6932. # self.save_project(filename)
  6933. if self.defaults["global_open_style"] is False:
  6934. self.file_opened.emit("pdf", filename)
  6935. self.file_saved.emit("pdf", filename)
  6936. def save_pdf(self, file_name, obj_selection):
  6937. p_size = self.defaults['global_workspaceT']
  6938. orientation = self.defaults['global_workspace_orientation']
  6939. color = 'black'
  6940. transparency_level = 1.0
  6941. self.pagesize = {}
  6942. self.pagesize.update(
  6943. {
  6944. 'Bounds': None,
  6945. 'A0': (841 * mm, 1189 * mm),
  6946. 'A1': (594 * mm, 841 * mm),
  6947. 'A2': (420 * mm, 594 * mm),
  6948. 'A3': (297 * mm, 420 * mm),
  6949. 'A4': (210 * mm, 297 * mm),
  6950. 'A5': (148 * mm, 210 * mm),
  6951. 'A6': (105 * mm, 148 * mm),
  6952. 'A7': (74 * mm, 105 * mm),
  6953. 'A8': (52 * mm, 74 * mm),
  6954. 'A9': (37 * mm, 52 * mm),
  6955. 'A10': (26 * mm, 37 * mm),
  6956. 'B0': (1000 * mm, 1414 * mm),
  6957. 'B1': (707 * mm, 1000 * mm),
  6958. 'B2': (500 * mm, 707 * mm),
  6959. 'B3': (353 * mm, 500 * mm),
  6960. 'B4': (250 * mm, 353 * mm),
  6961. 'B5': (176 * mm, 250 * mm),
  6962. 'B6': (125 * mm, 176 * mm),
  6963. 'B7': (88 * mm, 125 * mm),
  6964. 'B8': (62 * mm, 88 * mm),
  6965. 'B9': (44 * mm, 62 * mm),
  6966. 'B10': (31 * mm, 44 * mm),
  6967. 'C0': (917 * mm, 1297 * mm),
  6968. 'C1': (648 * mm, 917 * mm),
  6969. 'C2': (458 * mm, 648 * mm),
  6970. 'C3': (324 * mm, 458 * mm),
  6971. 'C4': (229 * mm, 324 * mm),
  6972. 'C5': (162 * mm, 229 * mm),
  6973. 'C6': (114 * mm, 162 * mm),
  6974. 'C7': (81 * mm, 114 * mm),
  6975. 'C8': (57 * mm, 81 * mm),
  6976. 'C9': (40 * mm, 57 * mm),
  6977. 'C10': (28 * mm, 40 * mm),
  6978. # American paper sizes
  6979. 'LETTER': (8.5 * inch, 11 * inch),
  6980. 'LEGAL': (8.5 * inch, 14 * inch),
  6981. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6982. # From https://en.wikipedia.org/wiki/Paper_size
  6983. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6984. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6985. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6986. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6987. 'LEDGER': (17 * inch, 11 * inch),
  6988. }
  6989. )
  6990. exported_svg = []
  6991. for obj in obj_selection:
  6992. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6993. scale_factor_x=None, scale_factor_y=None,
  6994. skew_factor_x=None, skew_factor_y=None,
  6995. mirror=None)
  6996. if obj.kind.lower() == 'gerber':
  6997. # color = self.defaults["gerber_plot_fill"][:-2]
  6998. color = obj.fill_color[:-2]
  6999. elif obj.kind.lower() == 'excellon':
  7000. color = '#C40000'
  7001. elif obj.kind.lower() == 'geometry':
  7002. color = self.defaults["global_draw_color"]
  7003. # Change the attributes of the exported SVG
  7004. # We don't need stroke-width
  7005. # We set opacity to maximum
  7006. # We set the colour to WHITE
  7007. root = ET.fromstring(svg_obj)
  7008. for child in root:
  7009. child.set('fill', str(color))
  7010. child.set('opacity', str(transparency_level))
  7011. child.set('stroke', str(color))
  7012. exported_svg.append(ET.tostring(root))
  7013. xmin = Inf
  7014. ymin = Inf
  7015. xmax = -Inf
  7016. ymax = -Inf
  7017. for obj in obj_selection:
  7018. try:
  7019. gxmin, gymin, gxmax, gymax = obj.bounds()
  7020. xmin = min([xmin, gxmin])
  7021. ymin = min([ymin, gymin])
  7022. xmax = max([xmax, gxmax])
  7023. ymax = max([ymax, gymax])
  7024. except Exception as e:
  7025. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7026. # Determine bounding area for svg export
  7027. bounds = [xmin, ymin, xmax, ymax]
  7028. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7029. # This contain the measure units
  7030. uom = obj_selection[0].units.lower()
  7031. # Define a boundary around SVG of about 1.0mm (~39mils)
  7032. if uom in "mm":
  7033. boundary = 1.0
  7034. else:
  7035. boundary = 0.0393701
  7036. # Convert everything to strings for use in the xml doc
  7037. svgwidth = str(size[0] + (2 * boundary))
  7038. svgheight = str(size[1] + (2 * boundary))
  7039. minx = str(bounds[0] - boundary)
  7040. miny = str(bounds[1] + boundary + size[1])
  7041. # Add a SVG Header and footer to the svg output from shapely
  7042. # The transform flips the Y Axis so that everything renders
  7043. # properly within svg apps such as inkscape
  7044. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7045. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7046. svg_header += 'width="' + svgwidth + uom + '" '
  7047. svg_header += 'height="' + svgheight + uom + '" '
  7048. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7049. svg_header += '>'
  7050. svg_header += '<g transform="scale(1,-1)">'
  7051. svg_footer = '</g> </svg>'
  7052. svg_elem = str(svg_header)
  7053. for svg_item in exported_svg:
  7054. svg_elem += str(svg_item)
  7055. svg_elem += str(svg_footer)
  7056. # Parse the xml through a xml parser just to add line feeds
  7057. # and to make it look more pretty for the output
  7058. doc = parse_xml_string(svg_elem)
  7059. doc_final = doc.toprettyxml()
  7060. try:
  7061. if self.defaults['units'].upper() == 'IN':
  7062. unit = inch
  7063. else:
  7064. unit = mm
  7065. doc_final = StringIO(doc_final)
  7066. drawing = svg2rlg(doc_final)
  7067. if p_size == 'Bounds':
  7068. renderPDF.drawToFile(drawing, file_name)
  7069. else:
  7070. if orientation == 'p':
  7071. page_size = portrait(self.pagesize[p_size])
  7072. else:
  7073. page_size = landscape(self.pagesize[p_size])
  7074. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7075. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7076. renderPDF.draw(drawing, my_canvas, 0, 0)
  7077. my_canvas.save()
  7078. except Exception as e:
  7079. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7080. return 'fail'
  7081. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7082. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7083. """
  7084. Exports a Geometry Object to an SVG file.
  7085. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7086. :param filename: Path to the SVG file to save to.
  7087. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7088. :return:
  7089. """
  7090. self.defaults.report_usage("export_svg()")
  7091. if filename is None:
  7092. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7093. is not None else self.defaults["global_last_folder"]
  7094. self.log.debug("export_svg()")
  7095. try:
  7096. obj = self.collection.get_by_name(str(obj_name))
  7097. except Exception:
  7098. # TODO: The return behavior has not been established... should raise exception?
  7099. return "Could not retrieve object: %s" % obj_name
  7100. with self.proc_container.new(_("Exporting SVG")) as proc:
  7101. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7102. # Determine bounding area for svg export
  7103. bounds = obj.bounds()
  7104. size = obj.size()
  7105. # Convert everything to strings for use in the xml doc
  7106. svgwidth = str(size[0])
  7107. svgheight = str(size[1])
  7108. minx = str(bounds[0])
  7109. miny = str(bounds[1] - size[1])
  7110. uom = obj.units.lower()
  7111. # Add a SVG Header and footer to the svg output from shapely
  7112. # The transform flips the Y Axis so that everything renders
  7113. # properly within svg apps such as inkscape
  7114. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7115. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7116. svg_header += 'width="' + svgwidth + uom + '" '
  7117. svg_header += 'height="' + svgheight + uom + '" '
  7118. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7119. svg_header += '<g transform="scale(1,-1)">'
  7120. svg_footer = '</g> </svg>'
  7121. svg_elem = svg_header + exported_svg + svg_footer
  7122. # Parse the xml through a xml parser just to add line feeds
  7123. # and to make it look more pretty for the output
  7124. svgcode = parse_xml_string(svg_elem)
  7125. svgcode = svgcode.toprettyxml()
  7126. try:
  7127. with open(filename, 'w') as fp:
  7128. fp.write(svgcode)
  7129. except PermissionError:
  7130. self.inform.emit('[WARNING] %s' %
  7131. _("Permission denied, saving not possible.\n"
  7132. "Most likely another app is holding the file open and not accessible."))
  7133. return 'fail'
  7134. if self.defaults["global_open_style"] is False:
  7135. self.file_opened.emit("SVG", filename)
  7136. self.file_saved.emit("SVG", filename)
  7137. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7138. def save_source_file(self, obj_name, filename, use_thread=True):
  7139. """
  7140. Exports a FlatCAM Object to an Gerber/Excellon file.
  7141. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7142. :param filename: Path to the Gerber file to save to.
  7143. :param use_thread: if to be run in a separate thread
  7144. :return:
  7145. """
  7146. self.defaults.report_usage("save source file()")
  7147. if filename is None:
  7148. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7149. is not None else self.defaults["global_last_folder"]
  7150. self.log.debug("save source file()")
  7151. obj = self.collection.get_by_name(obj_name)
  7152. file_string = StringIO(obj.source_file)
  7153. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7154. if file_string.getvalue() == '':
  7155. self.inform.emit('[ERROR_NOTCL] %s' %
  7156. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7157. return 'fail'
  7158. try:
  7159. with open(filename, 'w') as file:
  7160. file.writelines('G04*\n')
  7161. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7162. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7163. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7164. file.writelines('G04 Created on : %s*\n' % time_string)
  7165. for line in file_string:
  7166. file.writelines(line)
  7167. except PermissionError:
  7168. self.inform.emit('[WARNING] %s' %
  7169. _("Permission denied, saving not possible.\n"
  7170. "Most likely another app is holding the file open and not accessible."))
  7171. return 'fail'
  7172. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7173. """
  7174. Exports a Excellon Object to an Excellon file.
  7175. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7176. :param filename: Path to the Excellon file to save to.
  7177. :param local_use:
  7178. :param use_thread: if to be run in a separate thread
  7179. :return:
  7180. """
  7181. self.defaults.report_usage("export_excellon()")
  7182. if filename is None:
  7183. if self.defaults["global_last_save_folder"]:
  7184. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7185. else:
  7186. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7187. self.log.debug("export_excellon()")
  7188. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7189. self.defaults["excellon_exp_decimals"]
  7190. )
  7191. if local_use is None:
  7192. try:
  7193. obj = self.collection.get_by_name(str(obj_name))
  7194. except Exception:
  7195. return "Could not retrieve object: %s" % obj_name
  7196. else:
  7197. obj = local_use
  7198. if not isinstance(obj, ExcellonObject):
  7199. self.inform.emit('[ERROR_NOTCL] %s' %
  7200. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7201. return
  7202. # updated units
  7203. eunits = self.defaults["excellon_exp_units"]
  7204. ewhole = self.defaults["excellon_exp_integer"]
  7205. efract = self.defaults["excellon_exp_decimals"]
  7206. ezeros = self.defaults["excellon_exp_zeros"]
  7207. eformat = self.defaults["excellon_exp_format"]
  7208. slot_type = self.defaults["excellon_exp_slot_type"]
  7209. fc_units = self.defaults['units'].upper()
  7210. if fc_units == 'MM':
  7211. factor = 1 if eunits == 'METRIC' else 0.03937
  7212. else:
  7213. factor = 25.4 if eunits == 'METRIC' else 1
  7214. def make_excellon():
  7215. try:
  7216. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7217. header = 'M48\n'
  7218. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7219. (str(self.version), str(self.version_date))
  7220. header += ';Filename: %s' % str(obj_name) + '\n'
  7221. header += ';Created on : %s' % time_str + '\n'
  7222. if eformat == 'dec':
  7223. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7224. header += eunits + '\n'
  7225. for tool in obj.tools:
  7226. if eunits == 'METRIC':
  7227. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7228. tool=str(tool),
  7229. dec=2)
  7230. else:
  7231. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7232. tool=str(tool),
  7233. dec=4)
  7234. else:
  7235. if ezeros == 'LZ':
  7236. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7237. form='ndec', e_zeros='LZ', factor=factor,
  7238. slot_type=slot_type)
  7239. header += '%s,%s\n' % (eunits, 'LZ')
  7240. header += format_exc
  7241. for tool in obj.tools:
  7242. if eunits == 'METRIC':
  7243. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7244. tool=str(tool),
  7245. dec=2)
  7246. else:
  7247. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7248. tool=str(tool),
  7249. dec=4)
  7250. else:
  7251. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7252. form='ndec', e_zeros='TZ', factor=factor,
  7253. slot_type=slot_type)
  7254. header += '%s,%s\n' % (eunits, 'TZ')
  7255. header += format_exc
  7256. for tool in obj.tools:
  7257. if eunits == 'METRIC':
  7258. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7259. tool=str(tool),
  7260. dec=2)
  7261. else:
  7262. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7263. tool=str(tool),
  7264. dec=4)
  7265. header += '%\n'
  7266. footer = 'M30\n'
  7267. exported_excellon = header
  7268. exported_excellon += excellon_code
  7269. exported_excellon += footer
  7270. if local_use is None:
  7271. try:
  7272. with open(filename, 'w') as fp:
  7273. fp.write(exported_excellon)
  7274. except PermissionError:
  7275. self.inform.emit('[WARNING] %s' %
  7276. _("Permission denied, saving not possible.\n"
  7277. "Most likely another app is holding the file open and not accessible."))
  7278. return 'fail'
  7279. if self.defaults["global_open_style"] is False:
  7280. self.file_opened.emit("Excellon", filename)
  7281. self.file_saved.emit("Excellon", filename)
  7282. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7283. else:
  7284. return exported_excellon
  7285. except Exception as e:
  7286. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7287. return 'fail'
  7288. if use_thread is True:
  7289. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7290. def job_thread_exc(app_obj):
  7291. ret = make_excellon()
  7292. if ret == 'fail':
  7293. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7294. return
  7295. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7296. else:
  7297. eret = make_excellon()
  7298. if eret == 'fail':
  7299. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7300. return 'fail'
  7301. if local_use is not None:
  7302. return eret
  7303. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7304. """
  7305. Exports a Gerber Object to an Gerber file.
  7306. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7307. :param filename: Path to the Gerber file to save to.
  7308. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7309. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7310. :param use_thread: if to be run in a separate thread
  7311. :return:
  7312. """
  7313. self.defaults.report_usage("export_gerber()")
  7314. if filename is None:
  7315. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7316. is not None else self.defaults["global_last_folder"]
  7317. self.log.debug("export_gerber()")
  7318. if local_use is None:
  7319. try:
  7320. obj = self.collection.get_by_name(str(obj_name))
  7321. except Exception:
  7322. return "Could not retrieve object: %s" % obj_name
  7323. else:
  7324. obj = local_use
  7325. # updated units
  7326. gunits = self.defaults["gerber_exp_units"]
  7327. gwhole = self.defaults["gerber_exp_integer"]
  7328. gfract = self.defaults["gerber_exp_decimals"]
  7329. gzeros = self.defaults["gerber_exp_zeros"]
  7330. fc_units = self.defaults['units'].upper()
  7331. if fc_units == 'MM':
  7332. factor = 1 if gunits == 'MM' else 0.03937
  7333. else:
  7334. factor = 25.4 if gunits == 'MM' else 1
  7335. def make_gerber():
  7336. try:
  7337. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7338. header = 'G04*\n'
  7339. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7340. (str(self.version), str(self.version_date))
  7341. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7342. header += 'G04 Created on : %s*' % time_str + '\n'
  7343. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7344. header += "%MO{units}*%\n".format(units=gunits)
  7345. for apid in obj.apertures:
  7346. if obj.apertures[apid]['type'] == 'C':
  7347. header += "%ADD{apid}{type},{size}*%\n".format(
  7348. apid=str(apid),
  7349. type='C',
  7350. size=(factor * obj.apertures[apid]['size'])
  7351. )
  7352. elif obj.apertures[apid]['type'] == 'R':
  7353. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7354. apid=str(apid),
  7355. type='R',
  7356. width=(factor * obj.apertures[apid]['width']),
  7357. height=(factor * obj.apertures[apid]['height'])
  7358. )
  7359. elif obj.apertures[apid]['type'] == 'O':
  7360. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7361. apid=str(apid),
  7362. type='O',
  7363. width=(factor * obj.apertures[apid]['width']),
  7364. height=(factor * obj.apertures[apid]['height'])
  7365. )
  7366. header += '\n'
  7367. # obsolete units but some software may need it
  7368. if gunits == 'IN':
  7369. header += 'G70*\n'
  7370. else:
  7371. header += 'G71*\n'
  7372. # Absolute Mode
  7373. header += 'G90*\n'
  7374. header += 'G01*\n'
  7375. # positive polarity
  7376. header += '%LPD*%\n'
  7377. footer = 'M02*\n'
  7378. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7379. exported_gerber = header
  7380. exported_gerber += gerber_code
  7381. exported_gerber += footer
  7382. if local_use is None:
  7383. try:
  7384. with open(filename, 'w') as fp:
  7385. fp.write(exported_gerber)
  7386. except PermissionError:
  7387. self.inform.emit('[WARNING] %s' %
  7388. _("Permission denied, saving not possible.\n"
  7389. "Most likely another app is holding the file open and not accessible."))
  7390. return 'fail'
  7391. if self.defaults["global_open_style"] is False:
  7392. self.file_opened.emit("Gerber", filename)
  7393. self.file_saved.emit("Gerber", filename)
  7394. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7395. else:
  7396. return exported_gerber
  7397. except Exception as e:
  7398. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7399. return 'fail'
  7400. if use_thread is True:
  7401. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7402. def job_thread_grb(app_obj):
  7403. ret = make_gerber()
  7404. if ret == 'fail':
  7405. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7406. return
  7407. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7408. else:
  7409. gret = make_gerber()
  7410. if gret == 'fail':
  7411. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7412. return 'fail'
  7413. if local_use is not None:
  7414. return gret
  7415. def export_dxf(self, obj_name, filename, use_thread=True):
  7416. """
  7417. Exports a Geometry Object to an DXF file.
  7418. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7419. :param filename: Path to the DXF file to save to.
  7420. :param use_thread: if to be run in a separate thread
  7421. :return:
  7422. """
  7423. self.defaults.report_usage("export_dxf()")
  7424. if filename is None:
  7425. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7426. is not None else self.defaults["global_last_folder"]
  7427. self.log.debug("export_dxf()")
  7428. try:
  7429. obj = self.collection.get_by_name(str(obj_name))
  7430. except Exception:
  7431. # TODO: The return behavior has not been established... should raise exception?
  7432. return "Could not retrieve object: %s" % obj_name
  7433. def make_dxf():
  7434. try:
  7435. dxf_code = obj.export_dxf()
  7436. dxf_code.saveas(filename)
  7437. if self.defaults["global_open_style"] is False:
  7438. self.file_opened.emit("DXF", filename)
  7439. self.file_saved.emit("DXF", filename)
  7440. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7441. except Exception:
  7442. return 'fail'
  7443. if use_thread is True:
  7444. with self.proc_container.new(_("Exporting DXF")) as proc:
  7445. def job_thread_exc(app_obj):
  7446. ret_dxf_val = make_dxf()
  7447. if ret_dxf_val == 'fail':
  7448. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7449. return
  7450. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7451. else:
  7452. ret = make_dxf()
  7453. if ret == 'fail':
  7454. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7455. return
  7456. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7457. """
  7458. Adds a new Geometry Object to the projects and populates
  7459. it with shapes extracted from the SVG file.
  7460. :param plot: If True then the resulting object will be plotted on canvas
  7461. :param filename: Path to the SVG file.
  7462. :param geo_type: Type of FlatCAM object that will be created from SVG
  7463. :param outname: The name given to the resulting FlatCAM object
  7464. :return:
  7465. """
  7466. self.defaults.report_usage("import_svg()")
  7467. log.debug("App.import_svg()")
  7468. obj_type = ""
  7469. if geo_type is None or geo_type == "geometry":
  7470. obj_type = "geometry"
  7471. elif geo_type == "gerber":
  7472. obj_type = "gerber"
  7473. else:
  7474. self.inform.emit('[ERROR_NOTCL] %s' %
  7475. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7476. return
  7477. units = self.defaults['units'].upper()
  7478. def obj_init(geo_obj, app_obj):
  7479. geo_obj.import_svg(filename, obj_type, units=units)
  7480. geo_obj.multigeo = False
  7481. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7482. with self.proc_container.new(_("Importing SVG")) as proc:
  7483. # Object name
  7484. name = outname or filename.split('/')[-1].split('\\')[-1]
  7485. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7486. if ret == 'fail':
  7487. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7488. return 'fail'
  7489. # Register recent file
  7490. self.file_opened.emit("svg", filename)
  7491. # AppGUI feedback
  7492. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7493. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7494. """
  7495. Adds a new Geometry Object to the projects and populates
  7496. it with shapes extracted from the DXF file.
  7497. :param filename: Path to the DXF file.
  7498. :param geo_type: Type of FlatCAM object that will be created from DXF
  7499. :param outname: Name for the imported Geometry
  7500. :param plot: If True then the resulting object will be plotted on canvas
  7501. :return:
  7502. """
  7503. self.defaults.report_usage("import_dxf()")
  7504. obj_type = ""
  7505. if geo_type is None or geo_type == "geometry":
  7506. obj_type = "geometry"
  7507. elif geo_type == "gerber":
  7508. obj_type = geo_type
  7509. else:
  7510. self.inform.emit('[ERROR_NOTCL] %s' %
  7511. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7512. return
  7513. units = self.defaults['units'].upper()
  7514. def obj_init(geo_obj, app_obj):
  7515. geo_obj.import_dxf(filename, obj_type, units=units)
  7516. geo_obj.multigeo = False
  7517. with self.proc_container.new(_("Importing DXF")):
  7518. # Object name
  7519. name = outname or filename.split('/')[-1].split('\\')[-1]
  7520. ret = self.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7521. if ret == 'fail':
  7522. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7523. return 'fail'
  7524. # Register recent file
  7525. self.file_opened.emit("dxf", filename)
  7526. # AppGUI feedback
  7527. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7528. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7529. """
  7530. Opens a Gerber file, parses it and creates a new object for
  7531. it in the program. Thread-safe.
  7532. :param outname: Name of the resulting object. None causes the
  7533. name to be that of the file. Str.
  7534. :param filename: Gerber file filename
  7535. :type filename: str
  7536. :param plot: boolean, to plot or not the resulting object
  7537. :param from_tcl: True if run from Tcl Shell
  7538. :return: None
  7539. """
  7540. # How the object should be initialized
  7541. def obj_init(gerber_obj, app_obj):
  7542. assert isinstance(gerber_obj, GerberObject), \
  7543. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7544. # Opening the file happens here
  7545. try:
  7546. gerber_obj.parse_file(filename)
  7547. except IOError:
  7548. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7549. return "fail"
  7550. except ParseError as err:
  7551. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7552. app_obj.log.error(str(err))
  7553. return "fail"
  7554. except Exception as e:
  7555. log.debug("App.open_gerber() --> %s" % str(e))
  7556. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7557. msg += traceback.format_exc()
  7558. app_obj.inform.emit(msg)
  7559. return "fail"
  7560. if gerber_obj.is_empty():
  7561. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7562. _("Object is not Gerber file or empty. Aborting object creation."))
  7563. return "fail"
  7564. App.log.debug("open_gerber()")
  7565. with self.proc_container.new(_("Opening Gerber")):
  7566. # Object name
  7567. name = outname or filename.split('/')[-1].split('\\')[-1]
  7568. # # ## Object creation # ##
  7569. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7570. if ret_val == 'fail':
  7571. if from_tcl:
  7572. filename = self.defaults['global_tcl_path'] + '/' + name
  7573. ret_val = self.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7574. if ret_val == 'fail':
  7575. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7576. return 'fail'
  7577. # Register recent file
  7578. self.file_opened.emit("gerber", filename)
  7579. # AppGUI feedback
  7580. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7581. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7582. """
  7583. Opens an Excellon file, parses it and creates a new object for
  7584. it in the program. Thread-safe.
  7585. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7586. :param filename: Excellon file filename
  7587. :type filename: str
  7588. :param plot: boolean, to plot or not the resulting object
  7589. :param from_tcl: True if run from Tcl Shell
  7590. :return: None
  7591. """
  7592. App.log.debug("open_excellon()")
  7593. # How the object should be initialized
  7594. def obj_init(excellon_obj, app_obj):
  7595. try:
  7596. ret = excellon_obj.parse_file(filename=filename)
  7597. if ret == "fail":
  7598. log.debug("Excellon parsing failed.")
  7599. self.inform.emit('[ERROR_NOTCL] %s' %
  7600. _("This is not Excellon file."))
  7601. return "fail"
  7602. except IOError:
  7603. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7604. (_("Cannot open file"), filename))
  7605. log.debug("Could not open Excellon object.")
  7606. return "fail"
  7607. except Exception:
  7608. msg = '[ERROR_NOTCL] %s' % \
  7609. _("An internal error has occurred. See shell.\n")
  7610. msg += traceback.format_exc()
  7611. app_obj.inform.emit(msg)
  7612. return "fail"
  7613. ret = excellon_obj.create_geometry()
  7614. if ret == 'fail':
  7615. log.debug("Could not create geometry for Excellon object.")
  7616. return "fail"
  7617. for tool in excellon_obj.tools:
  7618. if excellon_obj.tools[tool]['solid_geometry']:
  7619. return
  7620. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7621. return "fail"
  7622. with self.proc_container.new(_("Opening Excellon.")):
  7623. # Object name
  7624. name = outname or filename.split('/')[-1].split('\\')[-1]
  7625. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7626. if ret_val == 'fail':
  7627. if from_tcl:
  7628. filename = self.defaults['global_tcl_path'] + '/' + name
  7629. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7630. if ret_val == 'fail':
  7631. self.inform.emit('[ERROR_NOTCL] %s' %
  7632. _('Open Excellon file failed. Probable not an Excellon file.'))
  7633. return
  7634. # Register recent file
  7635. self.file_opened.emit("excellon", filename)
  7636. # AppGUI feedback
  7637. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7638. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7639. """
  7640. Opens a G-gcode file, parses it and creates a new object for
  7641. it in the program. Thread-safe.
  7642. :param filename: G-code file filename
  7643. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7644. :param force_parsing:
  7645. :param plot: If True plot the object on canvas
  7646. :param from_tcl: True if run from Tcl Shell
  7647. :return: None
  7648. """
  7649. App.log.debug("open_gcode()")
  7650. # How the object should be initialized
  7651. def obj_init(job_obj, app_obj_):
  7652. """
  7653. :param job_obj: the resulting object
  7654. :type app_obj_: App
  7655. """
  7656. assert isinstance(app_obj_, App), \
  7657. "Initializer expected App, got %s" % type(app_obj_)
  7658. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7659. try:
  7660. f = open(filename)
  7661. gcode = f.read()
  7662. f.close()
  7663. except IOError:
  7664. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7665. return "fail"
  7666. job_obj.gcode = gcode
  7667. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7668. if gcode_ret == "fail":
  7669. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7670. return "fail"
  7671. job_obj.create_geometry()
  7672. with self.proc_container.new(_("Opening G-Code.")):
  7673. # Object name
  7674. name = outname or filename.split('/')[-1].split('\\')[-1]
  7675. # New object creation and file processing
  7676. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7677. if ret_val == 'fail':
  7678. if from_tcl:
  7679. filename = self.defaults['global_tcl_path'] + '/' + name
  7680. ret_val = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7681. if ret_val == 'fail':
  7682. self.inform.emit('[ERROR_NOTCL] %s' %
  7683. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7684. "Try to load it from File menu.\n "
  7685. "Attempting to create a FlatCAM CNCJob Object from "
  7686. "G-Code file failed during processing"))
  7687. return "fail"
  7688. # Register recent file
  7689. self.file_opened.emit("cncjob", filename)
  7690. # AppGUI feedback
  7691. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7692. def open_hpgl2(self, filename, outname=None):
  7693. """
  7694. Opens a HPGL2 file, parses it and creates a new object for
  7695. it in the program. Thread-safe.
  7696. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7697. :param filename: HPGL2 file filename
  7698. :return: None
  7699. """
  7700. filename = filename
  7701. # How the object should be initialized
  7702. def obj_init(geo_obj, app_obj):
  7703. assert isinstance(geo_obj, GeometryObject), \
  7704. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7705. # Opening the file happens here
  7706. obj = HPGL2(self)
  7707. try:
  7708. HPGL2.parse_file(obj, filename)
  7709. except IOError:
  7710. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7711. return "fail"
  7712. except ParseError as err:
  7713. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7714. app_obj.log.error(str(err))
  7715. return "fail"
  7716. except Exception as e:
  7717. log.debug("App.open_hpgl2() --> %s" % str(e))
  7718. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7719. msg += traceback.format_exc()
  7720. app_obj.inform.emit(msg)
  7721. return "fail"
  7722. geo_obj.multigeo = True
  7723. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7724. geo_obj.tools = deepcopy(obj.tools)
  7725. geo_obj.source_file = deepcopy(obj.source_file)
  7726. del obj
  7727. if not geo_obj.solid_geometry:
  7728. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7729. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7730. return "fail"
  7731. App.log.debug("open_hpgl2()")
  7732. with self.proc_container.new(_("Opening HPGL2")):
  7733. # Object name
  7734. name = outname or filename.split('/')[-1].split('\\')[-1]
  7735. # # ## Object creation # ##
  7736. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7737. if ret == 'fail':
  7738. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7739. return 'fail'
  7740. # Register recent file
  7741. self.file_opened.emit("geometry", filename)
  7742. # AppGUI feedback
  7743. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7744. def open_script(self, filename, outname=None, silent=False):
  7745. """
  7746. Opens a Script file, parses it and creates a new object for
  7747. it in the program. Thread-safe.
  7748. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7749. :param filename: Script file filename
  7750. :param silent: If True there will be no messages printed to StatusBar
  7751. :return: None
  7752. """
  7753. def obj_init(script_obj, app_obj):
  7754. assert isinstance(script_obj, ScriptObject), \
  7755. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7756. if silent is False:
  7757. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7758. try:
  7759. script_obj.parse_file(filename)
  7760. except IOError:
  7761. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7762. return "fail"
  7763. except ParseError as err:
  7764. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7765. app_obj.log.error(str(err))
  7766. return "fail"
  7767. except Exception as e:
  7768. log.debug("App.open_script() -> %s" % str(e))
  7769. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7770. msg += traceback.format_exc()
  7771. app_obj.inform.emit(msg)
  7772. return "fail"
  7773. App.log.debug("open_script()")
  7774. with self.proc_container.new(_("Opening TCL Script...")):
  7775. # Object name
  7776. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7777. # Object creation
  7778. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7779. if ret_val == 'fail':
  7780. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7781. ret_val = self.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7782. if ret_val == 'fail':
  7783. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7784. return 'fail'
  7785. # Register recent file
  7786. self.file_opened.emit("script", filename)
  7787. # AppGUI feedback
  7788. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7789. def open_config_file(self, filename, run_from_arg=None):
  7790. """
  7791. Loads a config file from the specified file.
  7792. :param filename: Name of the file from which to load.
  7793. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7794. :return: None
  7795. """
  7796. App.log.debug("Opening config file: " + filename)
  7797. if run_from_arg:
  7798. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7799. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7800. _("Opening FlatCAM Config file.")),
  7801. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7802. color=QtGui.QColor("gray"))
  7803. # # add the tab if it was closed
  7804. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7805. # # first clear previous text in text editor (if any)
  7806. # self.ui.text_editor_tab.code_editor.clear()
  7807. #
  7808. # # Switch plot_area to CNCJob tab
  7809. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7810. # close the Code editor if already open
  7811. if self.toggle_codeeditor:
  7812. self.on_toggle_code_editor()
  7813. self.on_toggle_code_editor()
  7814. try:
  7815. if filename:
  7816. f = QtCore.QFile(filename)
  7817. if f.open(QtCore.QIODevice.ReadOnly):
  7818. stream = QtCore.QTextStream(f)
  7819. code_edited = stream.readAll()
  7820. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7821. f.close()
  7822. except IOError:
  7823. App.log.error("Failed to open config file: %s" % filename)
  7824. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7825. (_("Failed to open config file"), filename))
  7826. return
  7827. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7828. """
  7829. Loads a project from the specified file.
  7830. 1) Loads and parses file
  7831. 2) Registers the file as recently opened.
  7832. 3) Calls on_file_new()
  7833. 4) Updates options
  7834. 5) Calls new_object() with the object's from_dict() as init method.
  7835. 6) Calls plot_all() if plot=True
  7836. :param filename: Name of the file from which to load.
  7837. :param run_from_arg: True if run for arguments
  7838. :param plot: If True plot all objects in the project
  7839. :param cli: Run from command line
  7840. :param from_tcl: True if run from Tcl Sehll
  7841. :return: None
  7842. """
  7843. App.log.debug("Opening project: " + filename)
  7844. # block autosaving while a project is loaded
  7845. self.block_autosave = True
  7846. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7847. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7848. if cli is None:
  7849. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7850. if run_from_arg:
  7851. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7852. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7853. _("Opening FlatCAM Project file.")),
  7854. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7855. color=QtGui.QColor("gray"))
  7856. # Open and parse an uncompressed Project file
  7857. try:
  7858. f = open(filename, 'r')
  7859. except IOError:
  7860. if from_tcl:
  7861. name = filename.split('/')[-1].split('\\')[-1]
  7862. filename = self.defaults['global_tcl_path'] + '/' + name
  7863. try:
  7864. f = open(filename, 'r')
  7865. except IOError:
  7866. log.error("Failed to open project file: %s" % filename)
  7867. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7868. return
  7869. else:
  7870. log.error("Failed to open project file: %s" % filename)
  7871. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7872. return
  7873. try:
  7874. d = json.load(f, object_hook=dict2obj)
  7875. except Exception as e:
  7876. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7877. (filename, str(e)))
  7878. f.close()
  7879. # Open and parse a compressed Project file
  7880. try:
  7881. with lzma.open(filename) as f:
  7882. file_content = f.read().decode('utf-8')
  7883. d = json.loads(file_content, object_hook=dict2obj)
  7884. except Exception as e:
  7885. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7886. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7887. return
  7888. # Clear the current project
  7889. # # NOT THREAD SAFE # ##
  7890. if run_from_arg is True:
  7891. pass
  7892. elif cli is True:
  7893. self.delete_selection_shape()
  7894. else:
  7895. self.on_file_new()
  7896. # Project options
  7897. self.options.update(d['options'])
  7898. self.project_filename = filename
  7899. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7900. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7901. if cli is None:
  7902. self.set_screen_units(self.options["units"])
  7903. # Re create objects
  7904. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7905. for obj in d['objs']:
  7906. try:
  7907. def obj_init(obj_inst, app_inst):
  7908. obj_inst.from_dict(obj)
  7909. App.log.debug("Recreating from opened project an %s object: %s" %
  7910. (obj['kind'].capitalize(), obj['options']['name']))
  7911. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7912. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7913. if cli is None:
  7914. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7915. obj['kind'].upper(),
  7916. obj['options']['name']
  7917. )
  7918. )
  7919. self.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7920. except Exception as e:
  7921. print('App.open_project() --> ' + str(e))
  7922. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7923. self.should_we_save = False
  7924. self.file_opened.emit("project", filename)
  7925. # restore autosaving after a project was loaded
  7926. self.block_autosave = False
  7927. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7928. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7929. if cli is None:
  7930. self.set_ui_title(name=self.project_filename)
  7931. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7932. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7933. """
  7934. Re-generates all plots from all objects.
  7935. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7936. :param muted: if True don't print messages
  7937. :param use_thread: if True will use threading for plotting the objects
  7938. :return: None
  7939. """
  7940. self.log.debug("Plot_all()")
  7941. if muted is not True:
  7942. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7943. for plot_obj in self.collection.get_list():
  7944. def worker_task(obj):
  7945. with self.proc_container.new("Plotting"):
  7946. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7947. if fit_view is True:
  7948. self.object_plotted.emit(obj)
  7949. if use_thread is True:
  7950. # Send to worker
  7951. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7952. else:
  7953. worker_task(plot_obj)
  7954. def register_folder(self, filename):
  7955. """
  7956. Register the last folder used by the app to open something
  7957. :param filename: the last folder is extracted from the filename
  7958. :return: None
  7959. """
  7960. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7961. def register_save_folder(self, filename):
  7962. """
  7963. Register the last folder used by the app to save something
  7964. :param filename: the last folder is extracted from the filename
  7965. :return: None
  7966. """
  7967. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7968. # def set_progress_bar(self, percentage, text=""):
  7969. # """
  7970. # Set a progress bar to a value (percentage)
  7971. #
  7972. # :param percentage: Value set to the progressbar
  7973. # :param text: Not used
  7974. # :return: None
  7975. # """
  7976. # self.ui.progress_bar.setValue(int(percentage))
  7977. def setup_recent_items(self):
  7978. """
  7979. Setup a dictionary with the recent files accessed, organized by type
  7980. :return:
  7981. """
  7982. icons = {
  7983. "gerber": self.resource_location + "/flatcam_icon16.png",
  7984. "excellon": self.resource_location + "/drill16.png",
  7985. 'geometry': self.resource_location + "/geometry16.png",
  7986. "cncjob": self.resource_location + "/cnc16.png",
  7987. "script": self.resource_location + "/script_new24.png",
  7988. "document": self.resource_location + "/notes16_1.png",
  7989. "project": self.resource_location + "/project16.png",
  7990. "svg": self.resource_location + "/geometry16.png",
  7991. "dxf": self.resource_location + "/dxf16.png",
  7992. "pdf": self.resource_location + "/pdf32.png",
  7993. "image": self.resource_location + "/image16.png"
  7994. }
  7995. try:
  7996. image_opener = self.image_tool.import_image
  7997. except AttributeError:
  7998. image_opener = None
  7999. openers = {
  8000. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8001. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8002. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8003. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8004. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8005. "document": None,
  8006. 'project': self.open_project,
  8007. 'svg': self.import_svg,
  8008. 'dxf': self.import_dxf,
  8009. 'image': image_opener,
  8010. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8011. }
  8012. # Open recent file for files
  8013. try:
  8014. f = open(self.data_path + '/recent.json')
  8015. except IOError:
  8016. App.log.error("Failed to load recent item list.")
  8017. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8018. return
  8019. try:
  8020. self.recent = json.load(f)
  8021. except json.errors.JSONDecodeError:
  8022. App.log.error("Failed to parse recent item list.")
  8023. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8024. f.close()
  8025. return
  8026. f.close()
  8027. # Open recent file for projects
  8028. try:
  8029. fp = open(self.data_path + '/recent_projects.json')
  8030. except IOError:
  8031. App.log.error("Failed to load recent project item list.")
  8032. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8033. return
  8034. try:
  8035. self.recent_projects = json.load(fp)
  8036. except json.errors.JSONDecodeError:
  8037. App.log.error("Failed to parse recent project item list.")
  8038. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8039. fp.close()
  8040. return
  8041. fp.close()
  8042. # Closure needed to create callbacks in a loop.
  8043. # Otherwise late binding occurs.
  8044. def make_callback(func, fname):
  8045. def opener():
  8046. func(fname)
  8047. return opener
  8048. def reset_recent_files():
  8049. # Reset menu
  8050. self.ui.recent.clear()
  8051. self.recent = []
  8052. try:
  8053. ff = open(self.data_path + '/recent.json', 'w')
  8054. except IOError:
  8055. App.log.error("Failed to open recent items file for writing.")
  8056. return
  8057. json.dump(self.recent, ff)
  8058. def reset_recent_projects():
  8059. # Reset menu
  8060. self.ui.recent_projects.clear()
  8061. self.recent_projects = []
  8062. try:
  8063. frp = open(self.data_path + '/recent_projects.json', 'w')
  8064. except IOError:
  8065. App.log.error("Failed to open recent projects items file for writing.")
  8066. return
  8067. json.dump(self.recent, frp)
  8068. # Reset menu
  8069. self.ui.recent.clear()
  8070. self.ui.recent_projects.clear()
  8071. # Create menu items for projects
  8072. for recent in self.recent_projects:
  8073. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8074. if recent['kind'] == 'project':
  8075. try:
  8076. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8077. # Attach callback
  8078. o = make_callback(openers[recent["kind"]], recent['filename'])
  8079. action.triggered.connect(o)
  8080. self.ui.recent_projects.addAction(action)
  8081. except KeyError:
  8082. App.log.error("Unsupported file type: %s" % recent["kind"])
  8083. # Last action in Recent Files menu is one that Clear the content
  8084. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8085. (_("Clear Recent projects")), self)
  8086. clear_action_proj.triggered.connect(reset_recent_projects)
  8087. self.ui.recent_projects.addSeparator()
  8088. self.ui.recent_projects.addAction(clear_action_proj)
  8089. # Create menu items for files
  8090. for recent in self.recent:
  8091. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8092. if recent['kind'] != 'project':
  8093. try:
  8094. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8095. # Attach callback
  8096. o = make_callback(openers[recent["kind"]], recent['filename'])
  8097. action.triggered.connect(o)
  8098. self.ui.recent.addAction(action)
  8099. except KeyError:
  8100. App.log.error("Unsupported file type: %s" % recent["kind"])
  8101. # Last action in Recent Files menu is one that Clear the content
  8102. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8103. (_("Clear Recent files")), self)
  8104. clear_action.triggered.connect(reset_recent_files)
  8105. self.ui.recent.addSeparator()
  8106. self.ui.recent.addAction(clear_action)
  8107. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8108. # self.ui.menufilerecent.set_submenu(recent_menu)
  8109. # recent_menu.show_all()
  8110. # self.ui.recent.show()
  8111. self.log.debug("Recent items list has been populated.")
  8112. def setup_component_editor(self):
  8113. """
  8114. Default text for the Selected tab when is not taken by the Object UI.
  8115. :return:
  8116. """
  8117. # label = QtWidgets.QLabel("Choose an item from Project")
  8118. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8119. sel_title = QtWidgets.QTextEdit(
  8120. _('<b>Shortcut Key List</b>'))
  8121. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8122. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8123. f_settings = QSettings("Open Source", "FlatCAM")
  8124. if f_settings.contains("notebook_font_size"):
  8125. fsize = f_settings.value('notebook_font_size', type=int)
  8126. else:
  8127. fsize = 12
  8128. tsize = fsize + int(fsize / 2)
  8129. # selected_text = (_('''
  8130. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8131. # </p>
  8132. #
  8133. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8134. # The normal flow when working in FlatCAM is the following:</span></p>
  8135. #
  8136. # <ol>
  8137. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8138. # file into
  8139. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8140. # even dragging and dropping the files on the AppGUI.<br />
  8141. # <br />
  8142. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8143. # drop of the
  8144. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  8145. # &nbsp;</li>
  8146. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8147. # and then
  8148. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8149. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8150. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8151. # <br />
  8152. # If the selection of the object is done on the canvas by single click instead, and the
  8153. # <strong>SELECTED TAB</strong>
  8154. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8155. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8156. # it even if it was out of focus.<br />
  8157. # <br />
  8158. # You can change the parameters in this screen and the flow direction is like this:<br />
  8159. # <br />
  8160. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8161. # <strong> Geometry Object
  8162. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8163. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8164. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8165. # </ol>
  8166. #
  8167. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8168. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8169. # <strong>F3</strong>.</span></p>
  8170. #
  8171. # ''').format(fsize=fsize, tsize=tsize))
  8172. selected_text = '''
  8173. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8174. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8175. {s1}</span></p>
  8176. <ol>
  8177. <li><span style="font-size:{fsize}px">{s2}<br />
  8178. <br />
  8179. {s3}</span><br />
  8180. &nbsp;</li>
  8181. <li><span style="font-size:{fsize}px">{s4}<br />
  8182. &nbsp;</li>
  8183. <br />
  8184. <li><span style="font-size:{fsize}px">{s5}<br />
  8185. &nbsp;</li>
  8186. <br />
  8187. <li><span style="font-size:{fsize}px">{s6}<br />
  8188. <br />
  8189. {s7}</span></li>
  8190. </ol>
  8191. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8192. '''.format(
  8193. title=_("Selected Tab - Choose an Item from Project Tab"),
  8194. subtitle=_("Details"),
  8195. s1=_("The normal flow when working in FlatCAM is the following:"),
  8196. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8197. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8198. "files on the AppGUI."),
  8199. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8200. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  8201. "actions offered within the app."),
  8202. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8203. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8204. "SELECTED TAB will be updated with the object properties according to its kind: "
  8205. "Gerber, Excellon, Geometry or CNCJob object."),
  8206. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8207. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8208. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8209. "the SELECTED TAB and populate it even if it was out of focus."),
  8210. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8211. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8212. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8213. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8214. "(again, done in SELECTED TAB) --> Save GCode."),
  8215. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8216. "or through its own key shortcut: <b>F3</b>."),
  8217. tsize=tsize,
  8218. fsize=fsize
  8219. )
  8220. sel_title.setText(selected_text)
  8221. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8222. self.ui.selected_scroll_area.setWidget(sel_title)
  8223. def setup_obj_classes(self):
  8224. """
  8225. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8226. class.
  8227. :return: None
  8228. """
  8229. FlatCAMObj.app = self
  8230. ObjectCollection.app = self
  8231. Gerber.app = self
  8232. Excellon.app = self
  8233. Geometry.app = self
  8234. CNCjob.app = self
  8235. FCProcess.app = self
  8236. FCProcessContainer.app = self
  8237. OptionsGroupUI.app = self
  8238. def version_check(self):
  8239. """
  8240. Checks for the latest version of the program. Alerts the
  8241. user if theirs is outdated. This method is meant to be run
  8242. in a separate thread.
  8243. :return: None
  8244. """
  8245. self.log.debug("version_check()")
  8246. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8247. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8248. App.version_url,
  8249. str(self.defaults['global_serial']),
  8250. str(self.version),
  8251. str(self.os),
  8252. urllib.parse.urlencode(self.defaults["global_stats"])
  8253. )
  8254. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8255. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8256. # urllib.parse.urlencode(self.defaults["global_stats"])
  8257. else:
  8258. # no_stats dict; just so it won't break things on website
  8259. no_ststs_dict = {}
  8260. no_ststs_dict["global_ststs"] = {}
  8261. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) + \
  8262. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8263. App.log.debug("Checking for updates @ %s" % full_url)
  8264. # ## Get the data
  8265. try:
  8266. f = urllib.request.urlopen(full_url)
  8267. except Exception:
  8268. # App.log.warning("Failed checking for latest version. Could not connect.")
  8269. self.log.warning("Failed checking for latest version. Could not connect.")
  8270. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8271. return
  8272. try:
  8273. data = json.load(f)
  8274. except Exception as e:
  8275. App.log.error("Could not parse information about latest version.")
  8276. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8277. App.log.debug("json.load(): %s" % str(e))
  8278. f.close()
  8279. return
  8280. f.close()
  8281. # ## Latest version?
  8282. if self.version >= data["version"]:
  8283. App.log.debug("FlatCAM is up to date!")
  8284. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8285. return
  8286. App.log.debug("Newer version available.")
  8287. self.message.emit(
  8288. _("Newer Version Available"),
  8289. '%s<br><br>><b>%s</b><br>%s' % (
  8290. _("There is a newer version of FlatCAM available for download:"),
  8291. str(data["name"]),
  8292. str(data["message"])
  8293. ),
  8294. _("info")
  8295. )
  8296. def on_plotcanvas_setup(self, container=None):
  8297. """
  8298. This is doing the setup for the plot area (canvas).
  8299. :param container: QT Widget where to install the canvas
  8300. :return: None
  8301. """
  8302. if container:
  8303. plot_container = container
  8304. else:
  8305. plot_container = self.ui.right_layout
  8306. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8307. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8308. self.is_legacy = True
  8309. self.defaults["global_graphic_engine"] = "2D"
  8310. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8311. else:
  8312. try:
  8313. self.plotcanvas = PlotCanvas(plot_container, self)
  8314. except Exception as er:
  8315. msg_txt = traceback.format_exc()
  8316. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8317. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8318. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8319. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8320. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8321. msg += msg_txt
  8322. self.inform.emit(msg)
  8323. return 'fail'
  8324. # So it can receive key presses
  8325. self.plotcanvas.native.setFocus()
  8326. if self.is_legacy is False:
  8327. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8328. # Set the mouse button for panning
  8329. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8330. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8331. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8332. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8333. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8334. # Keys over plot enabled
  8335. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8336. if self.defaults['global_cursor_type'] == 'small':
  8337. self.app_cursor = self.plotcanvas.new_cursor()
  8338. else:
  8339. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8340. if self.ui.grid_snap_btn.isChecked():
  8341. self.app_cursor.enabled = True
  8342. else:
  8343. self.app_cursor.enabled = False
  8344. if self.is_legacy is False:
  8345. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8346. else:
  8347. # will use the default Matplotlib axes
  8348. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8349. def on_zoom_fit(self, event):
  8350. """
  8351. Callback for zoom-fit request. This can be either from the corresponding
  8352. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8353. with axes limits from the geometry bounds of all objects.
  8354. :param event: Ignored.
  8355. :return: None
  8356. """
  8357. if self.is_legacy is False:
  8358. self.plotcanvas.fit_view()
  8359. else:
  8360. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8361. width = xmax - xmin
  8362. height = ymax - ymin
  8363. xmin -= 0.05 * width
  8364. xmax += 0.05 * width
  8365. ymin -= 0.05 * height
  8366. ymax += 0.05 * height
  8367. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8368. def on_zoom_in(self):
  8369. """
  8370. Callback for zoom-in request.
  8371. :return:
  8372. """
  8373. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8374. def on_zoom_out(self):
  8375. """
  8376. Callback for zoom-out request.
  8377. :return:
  8378. """
  8379. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8380. def disable_all_plots(self):
  8381. self.defaults.report_usage("disable_all_plots()")
  8382. self.disable_plots(self.collection.get_list())
  8383. self.inform.emit('[success] %s' %
  8384. _("All plots disabled."))
  8385. def disable_other_plots(self):
  8386. self.defaults.report_usage("disable_other_plots()")
  8387. self.disable_plots(self.collection.get_non_selected())
  8388. self.inform.emit('[success] %s' %
  8389. _("All non selected plots disabled."))
  8390. def enable_all_plots(self):
  8391. self.defaults.report_usage("enable_all_plots()")
  8392. self.enable_plots(self.collection.get_list())
  8393. self.inform.emit('[success] %s' %
  8394. _("All plots enabled."))
  8395. def on_enable_sel_plots(self):
  8396. log.debug("App.on_enable_sel_plot()")
  8397. object_list = self.collection.get_selected()
  8398. self.enable_plots(objects=object_list)
  8399. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8400. def on_disable_sel_plots(self):
  8401. log.debug("App.on_disable_sel_plot()")
  8402. # self.inform.emit(_("Disabling plots ..."))
  8403. object_list = self.collection.get_selected()
  8404. self.disable_plots(objects=object_list)
  8405. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8406. def enable_plots(self, objects):
  8407. """
  8408. Enable plots
  8409. :param objects: list of AppObjects to be enabled
  8410. :return:
  8411. """
  8412. log.debug("Enabling plots ...")
  8413. # self.inform.emit(_("Working ..."))
  8414. for obj in objects:
  8415. if obj.options['plot'] is False:
  8416. obj.options.set_change_callback(lambda x: None)
  8417. obj.options['plot'] = True
  8418. try:
  8419. # only the Gerber obj has on_plot_cb_click() method
  8420. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8421. # disable this cb while disconnected,
  8422. # in case the operation takes time the user is not allowed to change it
  8423. obj.ui.plot_cb.setDisabled(True)
  8424. except AttributeError:
  8425. pass
  8426. obj.set_form_item("plot")
  8427. try:
  8428. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8429. obj.ui.plot_cb.setDisabled(False)
  8430. except AttributeError:
  8431. pass
  8432. obj.options.set_change_callback(obj.on_options_change)
  8433. def worker_task(objs):
  8434. with self.proc_container.new(_("Enabling plots ...")):
  8435. for plot_obj in objs:
  8436. # obj.options['plot'] = True
  8437. if isinstance(plot_obj, CNCJobObject):
  8438. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8439. else:
  8440. plot_obj.plot(visible=True)
  8441. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8442. # self.plots_updated.emit()
  8443. def disable_plots(self, objects):
  8444. """
  8445. Disables plots
  8446. :param objects: list of AppObjects to be disabled
  8447. :return:
  8448. """
  8449. # if no objects selected then do nothing
  8450. if not self.collection.get_selected():
  8451. return
  8452. log.debug("Disabling plots ...")
  8453. # self.inform.emit(_("Working ..."))
  8454. for obj in objects:
  8455. if obj.options['plot'] is True:
  8456. obj.options.set_change_callback(lambda x: None)
  8457. obj.options['plot'] = False
  8458. try:
  8459. # only the Gerber obj has on_plot_cb_click() method
  8460. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8461. obj.ui.plot_cb.setDisabled(True)
  8462. except AttributeError:
  8463. pass
  8464. obj.set_form_item("plot")
  8465. try:
  8466. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8467. obj.ui.plot_cb.setDisabled(False)
  8468. except AttributeError:
  8469. pass
  8470. obj.options.set_change_callback(obj.on_options_change)
  8471. try:
  8472. self.delete_selection_shape()
  8473. except Exception as e:
  8474. log.debug("App.disable_plots() --> %s" % str(e))
  8475. # self.plots_updated.emit()
  8476. def worker_task(objs):
  8477. with self.proc_container.new(_("Disabling plots ...")):
  8478. for plot_obj in objs:
  8479. # obj.options['plot'] = True
  8480. if isinstance(plot_obj, CNCJobObject):
  8481. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8482. else:
  8483. plot_obj.plot(visible=False)
  8484. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8485. def toggle_plots(self, objects):
  8486. """
  8487. Toggle plots visibility
  8488. :param objects: list of AppObjects for which to be toggled the visibility
  8489. :return: None
  8490. """
  8491. # if no objects selected then do nothing
  8492. if not self.collection.get_selected():
  8493. return
  8494. log.debug("Toggling plots ...")
  8495. self.inform.emit(_("Working ..."))
  8496. for obj in objects:
  8497. if obj.options['plot'] is False:
  8498. obj.options['plot'] = True
  8499. else:
  8500. obj.options['plot'] = False
  8501. self.plots_updated.emit()
  8502. def clear_plots(self):
  8503. """
  8504. Clear the plots
  8505. :return: None
  8506. """
  8507. objects = self.collection.get_list()
  8508. for obj in objects:
  8509. obj.clear(obj == objects[-1])
  8510. # Clear pool to free memory
  8511. self.clear_pool()
  8512. def on_set_color_action_triggered(self):
  8513. """
  8514. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8515. :return:
  8516. """
  8517. new_color = self.defaults['gerber_plot_fill']
  8518. clicked_action = self.sender()
  8519. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8520. act_name = clicked_action.text()
  8521. sel_obj_list = self.collection.get_selected()
  8522. if not sel_obj_list:
  8523. return
  8524. # a default value, I just chose this one
  8525. alpha_level = 'BF'
  8526. for sel_obj in sel_obj_list:
  8527. if sel_obj.kind == 'excellon':
  8528. alpha_level = str(hex(
  8529. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8530. elif sel_obj.kind == 'gerber':
  8531. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8532. elif sel_obj.kind == 'geometry':
  8533. alpha_level = 'FF'
  8534. else:
  8535. log.debug(
  8536. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8537. continue
  8538. sel_obj.alpha_level = alpha_level
  8539. if act_name == _('Red'):
  8540. new_color = '#FF0000' + alpha_level
  8541. if act_name == _('Blue'):
  8542. new_color = '#0000FF' + alpha_level
  8543. if act_name == _('Yellow'):
  8544. new_color = '#FFDF00' + alpha_level
  8545. if act_name == _('Green'):
  8546. new_color = '#00FF00' + alpha_level
  8547. if act_name == _('Purple'):
  8548. new_color = '#FF00FF' + alpha_level
  8549. if act_name == _('Brown'):
  8550. new_color = '#A52A2A' + alpha_level
  8551. if act_name == _('White'):
  8552. new_color = '#FFFFFF' + alpha_level
  8553. if act_name == _('Black'):
  8554. new_color = '#000000' + alpha_level
  8555. if act_name == _('Custom'):
  8556. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8557. c_dialog = QtWidgets.QColorDialog()
  8558. plot_fill_color = c_dialog.getColor(initial=new_color)
  8559. if plot_fill_color.isValid() is False:
  8560. return
  8561. new_color = str(plot_fill_color.name()) + alpha_level
  8562. if act_name == _("Default"):
  8563. for sel_obj in sel_obj_list:
  8564. if sel_obj.kind == 'excellon':
  8565. new_color = self.defaults['excellon_plot_fill']
  8566. new_line_color = self.defaults['excellon_plot_line']
  8567. elif sel_obj.kind == 'gerber':
  8568. new_color = self.defaults['gerber_plot_fill']
  8569. new_line_color = self.defaults['gerber_plot_line']
  8570. elif sel_obj.kind == 'geometry':
  8571. new_color = self.defaults['geometry_plot_line']
  8572. new_line_color = self.defaults['geometry_plot_line']
  8573. else:
  8574. log.debug(
  8575. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8576. continue
  8577. sel_obj.fill_color = new_color
  8578. sel_obj.outline_color = new_line_color
  8579. sel_obj.shapes.redraw(
  8580. update_colors=(new_color, new_line_color)
  8581. )
  8582. return
  8583. if act_name == _("Opacity"):
  8584. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8585. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8586. if ok_button:
  8587. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8588. for sel_obj in sel_obj_list:
  8589. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8590. sel_obj.shapes.redraw(
  8591. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8592. )
  8593. return
  8594. new_line_color = color_variant(new_color[:7], 0.7)
  8595. if act_name == _("White"):
  8596. new_line_color = color_variant("#dedede", 0.7)
  8597. for sel_obj in sel_obj_list:
  8598. sel_obj.fill_color = new_color
  8599. sel_obj.outline_color = new_line_color
  8600. sel_obj.shapes.redraw(
  8601. update_colors=(new_color, new_line_color)
  8602. )
  8603. def generate_cnc_job(self, objects):
  8604. """
  8605. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8606. :param objects: Selected objects in the Project Tab
  8607. :return:
  8608. """
  8609. self.defaults.report_usage("generate_cnc_job()")
  8610. # for obj in objects:
  8611. # obj.generatecncjob()
  8612. for obj in objects:
  8613. obj.on_generatecnc_button_click()
  8614. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8615. """
  8616. Saves the current project to the specified file.
  8617. :param filename: Name of the file in which to save.
  8618. :type filename: str
  8619. :param quit_action: if the project saving will be followed by an app quit; boolean
  8620. :param silent: if True will not display status messages
  8621. :param from_tcl True is run from Tcl Shell
  8622. :return: None
  8623. """
  8624. self.log.debug("save_project()")
  8625. self.save_in_progress = True
  8626. with self.proc_container.new(_("Saving FlatCAM Project")):
  8627. # Capture the latest changes
  8628. # Current object
  8629. try:
  8630. current_object = self.collection.get_active()
  8631. if current_object:
  8632. current_object.read_form()
  8633. except Exception as e:
  8634. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8635. pass
  8636. # Serialize the whole project
  8637. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8638. "options": self.options,
  8639. "version": self.version}
  8640. if self.defaults["global_save_compressed"] is True:
  8641. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8642. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8643. # # Write
  8644. f.write(g)
  8645. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8646. else:
  8647. # Open file
  8648. try:
  8649. f = open(filename, 'w')
  8650. except IOError:
  8651. App.log.error("Failed to open file for saving: %s", filename)
  8652. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8653. return
  8654. # Write
  8655. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8656. f.close()
  8657. # verification of the saved project
  8658. # Open and parse
  8659. try:
  8660. saved_f = open(filename, 'r')
  8661. except IOError:
  8662. if silent is False:
  8663. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8664. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8665. return
  8666. try:
  8667. saved_d = json.load(saved_f, object_hook=dict2obj)
  8668. except Exception:
  8669. if silent is False:
  8670. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8671. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8672. f.close()
  8673. return
  8674. saved_f.close()
  8675. if silent is False:
  8676. if 'version' in saved_d:
  8677. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8678. else:
  8679. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8680. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8681. tb_settings = QSettings("Open Source", "FlatCAM")
  8682. lock_state = self.ui.lock_action.isChecked()
  8683. tb_settings.setValue('toolbar_lock', lock_state)
  8684. # This will write the setting to the platform specific storage.
  8685. del tb_settings
  8686. # if quit:
  8687. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8688. # t.start()
  8689. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8690. def start_delayed_quit(self, delay, filename, should_quit=None):
  8691. """
  8692. :param delay: period of checking if project file size is more than zero; in seconds
  8693. :param filename: the name of the project file to be checked periodically for size more than zero
  8694. :param should_quit: if the task finished will be followed by an app quit; boolean
  8695. :return:
  8696. """
  8697. to_quit = should_quit
  8698. self.save_timer = QtCore.QTimer()
  8699. self.save_timer.setInterval(delay)
  8700. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8701. self.save_timer.start()
  8702. def check_project_file_size(self, filename, should_quit=None):
  8703. """
  8704. :param filename: the name of the project file to be checked periodically for size more than zero
  8705. :param should_quit: will quit the app if True; boolean
  8706. :return:
  8707. """
  8708. try:
  8709. if os.stat(filename).st_size > 0:
  8710. self.save_in_progress = False
  8711. self.save_timer.stop()
  8712. if should_quit:
  8713. self.app_quit.emit()
  8714. except Exception:
  8715. traceback.print_exc()
  8716. def save_project_auto(self):
  8717. """
  8718. Called periodically to save the project.
  8719. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8720. # progress.
  8721. :return:
  8722. """
  8723. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8724. self.on_file_saveproject()
  8725. def save_project_auto_update(self):
  8726. """
  8727. Update the auto save time interval value.
  8728. :return:
  8729. """
  8730. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8731. try:
  8732. if self.autosave_timer.isActive():
  8733. self.autosave_timer.stop()
  8734. except Exception:
  8735. pass
  8736. if self.defaults['global_autosave'] is True:
  8737. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8738. self.autosave_timer.start()
  8739. def on_options_app2project(self):
  8740. """
  8741. Callback for Options->Transfer Options->App=>Project. Copies options
  8742. from application defaults to project defaults.
  8743. :return: None
  8744. """
  8745. self.defaults.report_usage("on_options_app2project")
  8746. self.preferencesUiManager.defaults_read_form()
  8747. self.options.update(self.defaults)
  8748. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8749. """
  8750. Shows a message on the FlatCAM Shell
  8751. :param msg: Message to display.
  8752. :param show: Opens the shell.
  8753. :param error: Shows the message as an error.
  8754. :param warning: Shows the message as an warning.
  8755. :param success: Shows the message as an success.
  8756. :param selected: Indicate that something was selected on canvas
  8757. :return: None
  8758. """
  8759. if show:
  8760. self.ui.shell_dock.show()
  8761. try:
  8762. if error:
  8763. self.shell.append_error(msg + "\n")
  8764. elif warning:
  8765. self.shell.append_warning(msg + "\n")
  8766. elif success:
  8767. self.shell.append_success(msg + "\n")
  8768. elif selected:
  8769. self.shell.append_selected(msg + "\n")
  8770. else:
  8771. self.shell.append_output(msg + "\n")
  8772. except AttributeError:
  8773. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8774. class ArgsThread(QtCore.QObject):
  8775. open_signal = pyqtSignal(list)
  8776. start = pyqtSignal()
  8777. stop = pyqtSignal()
  8778. if sys.platform == 'win32':
  8779. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8780. else:
  8781. address = ('/tmp/testipc', 'AF_UNIX')
  8782. def __init__(self):
  8783. super(ArgsThread, self).__init__()
  8784. self.listener = None
  8785. self.thread_exit = False
  8786. self.start.connect(self.run)
  8787. self.stop.connect(self.close_listener)
  8788. def my_loop(self, address):
  8789. try:
  8790. self.listener = Listener(*address)
  8791. while self.thread_exit is False:
  8792. conn = self.listener.accept()
  8793. self.serve(conn)
  8794. except socket.error:
  8795. try:
  8796. conn = Client(*address)
  8797. conn.send(sys.argv)
  8798. conn.send('close')
  8799. # close the current instance only if there are args
  8800. if len(sys.argv) > 1:
  8801. try:
  8802. self.listener.close()
  8803. except Exception:
  8804. pass
  8805. sys.exit()
  8806. except ConnectionRefusedError:
  8807. if sys.platform == 'win32':
  8808. pass
  8809. else:
  8810. os.system('rm /tmp/testipc')
  8811. self.listener = Listener(*address)
  8812. while True:
  8813. conn = self.listener.accept()
  8814. self.serve(conn)
  8815. def serve(self, conn):
  8816. while self.thread_exit is False:
  8817. msg = conn.recv()
  8818. if msg == 'close':
  8819. break
  8820. self.open_signal.emit(msg)
  8821. conn.close()
  8822. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8823. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8824. @pyqtSlot()
  8825. def run(self):
  8826. self.my_loop(self.address)
  8827. @pyqtSlot()
  8828. def close_listener(self):
  8829. self.thread_exit = True
  8830. self.listener.close()
  8831. # end of file