App_Main.py 447 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985
  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. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Various
  37. from Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from AppDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM defaults (preferences)
  45. from defaults import FlatCAMDefaults
  46. # FlatCAM Objects
  47. from AppGUI.preferences.OptionsGroupUI import OptionsGroupUI
  48. from AppGUI.preferences.PreferencesUIManager import PreferencesUIManager
  49. from AppObjects.ObjectCollection import *
  50. from AppObjects.FlatCAMObj import FlatCAMObj
  51. from AppObjects.AppObject import AppObject
  52. # FlatCAM Parsing files
  53. from AppParsers.ParseExcellon import Excellon
  54. from AppParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM AppGUI
  57. from AppGUI.PlotCanvas import *
  58. from AppGUI.PlotCanvasLegacy import *
  59. from AppGUI.MainGUI import *
  60. from AppGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  61. # FlatCAM Pre-processors
  62. from AppPreProcessor import load_preprocessors
  63. # FlatCAM AppEditors
  64. from AppEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  65. from AppEditors.FlatCAMExcEditor import FlatCAMExcEditor
  66. from AppEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  67. from AppEditors.FlatCAMTextEditor import TextEditor
  68. from AppParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from AppProcess import *
  71. from AppWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from AppTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import AppTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. from win32comext.shell import shell, shellcon
  81. fcTranslate.apply_language('strings')
  82. if '_' not in builtins.__dict__:
  83. _ = gettext.gettext
  84. class App(QtCore.QObject):
  85. """
  86. The main application class. The constructor starts the GUI and all other classes used by the program.
  87. """
  88. # ###############################################################################################################
  89. # ########################################## App ################################################################
  90. # ###############################################################################################################
  91. # ###############################################################################################################
  92. # ######################################### LOGGING #############################################################
  93. # ###############################################################################################################
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ###############################################################################################################
  102. # #################################### Get Cmd Line Options #####################################################
  103. # ###############################################################################################################
  104. cmd_line_shellfile = ''
  105. cmd_line_shellvar = ''
  106. cmd_line_headless = None
  107. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  108. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  109. "FlatCam.py --headless=1"
  110. try:
  111. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  112. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  113. "shellvar=",
  114. "headless=",
  115. "multiprocessing-fork="])
  116. except getopt.GetoptError:
  117. print(cmd_line_help)
  118. sys.exit(2)
  119. for opt, arg in cmd_line_options:
  120. if opt == '-h':
  121. print(cmd_line_help)
  122. sys.exit()
  123. elif opt == '--shellfile':
  124. cmd_line_shellfile = arg
  125. elif opt == '--shellvar':
  126. cmd_line_shellvar = arg
  127. elif opt == '--headless':
  128. try:
  129. cmd_line_headless = eval(arg)
  130. except NameError:
  131. pass
  132. # ###############################################################################################################
  133. # ################################### Version and VERSION DATE ##################################################
  134. # ###############################################################################################################
  135. version = 8.993
  136. version_date = "2020/08/01"
  137. beta = True
  138. engine = '3D'
  139. # current date now
  140. date = str(datetime.today()).rpartition('.')[0]
  141. date = ''.join(c for c in date if c not in ':-')
  142. date = date.replace(' ', '_')
  143. # ###############################################################################################################
  144. # ############################################ URLS's ###########################################################
  145. # ###############################################################################################################
  146. # URL for update checks and statistics
  147. version_url = "http://flatcam.org/version"
  148. # App URL
  149. app_url = "http://flatcam.org"
  150. # Manual URL
  151. manual_url = "http://flatcam.org/manual/index.html"
  152. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  153. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  154. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  155. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  156. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  157. # this variable will hold the project status
  158. # if True it will mean that the project was modified and not saved
  159. should_we_save = False
  160. # flag is True if saving action has been triggered
  161. save_in_progress = False
  162. # ###############################################################################################################
  163. # ####################################### APP Signals ######################################################
  164. # ###############################################################################################################
  165. # Inform the user
  166. # Handled by:
  167. # * App.info() --> Print on the status bar
  168. inform = QtCore.pyqtSignal(str)
  169. app_quit = QtCore.pyqtSignal()
  170. # General purpose background task
  171. worker_task = QtCore.pyqtSignal(dict)
  172. # File opened
  173. # Handled by:
  174. # * register_folder()
  175. # * register_recent()
  176. # Note: Setting the parameters to unicode does not seem
  177. # to have an effect. Then are received as Qstring
  178. # anyway.
  179. # File type and filename
  180. file_opened = QtCore.pyqtSignal(str, str)
  181. # File type and filename
  182. file_saved = QtCore.pyqtSignal(str, str)
  183. # Percentage of progress
  184. progress = QtCore.pyqtSignal(int)
  185. # Emitted when a new object has been added or deleted from/to the collection
  186. object_status_changed = QtCore.pyqtSignal(object, str, str)
  187. message = QtCore.pyqtSignal(str, str, str)
  188. # Emmited when shell command is finished(one command only)
  189. shell_command_finished = QtCore.pyqtSignal(object)
  190. # Emitted when multiprocess pool has been recreated
  191. pool_recreated = QtCore.pyqtSignal(object)
  192. # Emitted when an unhandled exception happens
  193. # in the worker task.
  194. thread_exception = QtCore.pyqtSignal(object)
  195. # used to signal that there are arguments for the app
  196. args_at_startup = QtCore.pyqtSignal(list)
  197. # a reusable signal to replot a list of objects
  198. # should be disconnected after use so it can be reused
  199. replot_signal = pyqtSignal(list)
  200. # signal emitted when jumping
  201. jump_signal = pyqtSignal(tuple)
  202. # signal emitted when jumping
  203. locate_signal = pyqtSignal(tuple, str)
  204. # close app signal
  205. close_app_signal = pyqtSignal()
  206. # will perform the cleanup operation after a Graceful Exit
  207. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  208. # graphic residues behind
  209. cleanup = pyqtSignal()
  210. def __init__(self, user_defaults=True):
  211. """
  212. Starts the application.
  213. :return: app
  214. :rtype: App
  215. """
  216. super().__init__()
  217. App.log.info("FlatCAM Starting...")
  218. self.main_thread = QtWidgets.QApplication.instance().thread()
  219. # ############################################################################################################
  220. # ################# Setup the listening thread for another instance launching with args ######################
  221. # ############################################################################################################
  222. if sys.platform == 'win32' or sys.platform == 'linux':
  223. # make sure the thread is stored by using a self. otherwise it's garbage collected
  224. self.th = QtCore.QThread()
  225. self.th.start(priority=QtCore.QThread.LowestPriority)
  226. self.new_launch = ArgsThread()
  227. self.new_launch.open_signal[list].connect(self.on_startup_args)
  228. self.new_launch.moveToThread(self.th)
  229. self.new_launch.start.emit()
  230. # ############################################################################################################
  231. # ########################################## OS-specific #####################################################
  232. # ############################################################################################################
  233. portable = False
  234. # Folder for user settings.
  235. if sys.platform == 'win32':
  236. if platform.architecture()[0] == '32bit':
  237. App.log.debug("Win32!")
  238. else:
  239. App.log.debug("Win64!")
  240. # #######################################################################################################
  241. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  242. # #######################################################################################################
  243. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  244. try:
  245. with open(config_file, 'r'):
  246. pass
  247. except FileNotFoundError:
  248. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  249. try:
  250. with open(config_file, 'r') as f:
  251. try:
  252. for line in f:
  253. param = str(line).replace('\n', '').rpartition('=')
  254. if param[0] == 'portable':
  255. try:
  256. portable = eval(param[2])
  257. except NameError:
  258. portable = False
  259. if param[0] == 'headless':
  260. if param[2].lower() == 'true':
  261. self.cmd_line_headless = 1
  262. else:
  263. self.cmd_line_headless = None
  264. except Exception as e:
  265. log.debug('App.__init__() -->%s' % str(e))
  266. return
  267. except FileNotFoundError as e:
  268. log.debug(str(e))
  269. pass
  270. if portable is False:
  271. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  272. else:
  273. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  274. self.os = 'windows'
  275. else: # Linux/Unix/MacOS
  276. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  277. self.os = 'unix'
  278. # ############################################################################################################
  279. # ################################# Setup folders and files ##################################################
  280. # ############################################################################################################
  281. if not os.path.exists(self.data_path):
  282. os.makedirs(self.data_path)
  283. App.log.debug('Created data folder: ' + self.data_path)
  284. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  285. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  286. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  287. if not os.path.exists(self.preprocessorpaths):
  288. os.makedirs(self.preprocessorpaths)
  289. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  290. # create geo_tools_db.FlatDB file if there is none
  291. try:
  292. f = open(self.data_path + '/geo_tools_db.FlatDB')
  293. f.close()
  294. except IOError:
  295. App.log.debug('Creating empty geo_tool_db.FlatDB')
  296. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  297. json.dump({}, f)
  298. f.close()
  299. # create current_defaults.FlatConfig file if there is none
  300. try:
  301. f = open(self.data_path + '/current_defaults.FlatConfig')
  302. f.close()
  303. except IOError:
  304. App.log.debug('Creating empty current_defaults.FlatConfig')
  305. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  306. json.dump({}, f)
  307. f.close()
  308. # Write factory_defaults.FlatConfig file to disk
  309. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  310. # create a recent files json file if there is none
  311. try:
  312. f = open(self.data_path + '/recent.json')
  313. f.close()
  314. except IOError:
  315. App.log.debug('Creating empty recent.json')
  316. f = open(self.data_path + '/recent.json', 'w')
  317. json.dump([], f)
  318. f.close()
  319. # create a recent projects json file if there is none
  320. try:
  321. fp = open(self.data_path + '/recent_projects.json')
  322. fp.close()
  323. except IOError:
  324. App.log.debug('Creating empty recent_projects.json')
  325. fp = open(self.data_path + '/recent_projects.json', 'w')
  326. json.dump([], fp)
  327. fp.close()
  328. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. log.debug("Application path is " + self.app_home)
  332. log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # ############################################################################################################
  338. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  339. # ############################################################################################################
  340. self.defaults = FlatCAMDefaults()
  341. self.defaults["root_folder_path"] = self.app_home
  342. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  343. if user_defaults:
  344. self.defaults.load(filename=current_defaults_path)
  345. if self.defaults['units'] == 'MM':
  346. self.decimals = int(self.defaults['decimals_metric'])
  347. else:
  348. self.decimals = int(self.defaults['decimals_inch'])
  349. if self.defaults["global_gray_icons"] is False:
  350. self.resource_location = 'assets/resources'
  351. else:
  352. self.resource_location = 'assets/resources/dark_resources'
  353. self.current_units = self.defaults['units']
  354. # ###########################################################################################################
  355. # #################################### SETUP OBJECT CLASSES #################################################
  356. # ###########################################################################################################
  357. self.setup_obj_classes()
  358. # ###########################################################################################################
  359. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  360. # ###########################################################################################################
  361. self.pool = Pool()
  362. # ###########################################################################################################
  363. # ###################################### Setting the Splash Screen ##########################################
  364. # ###########################################################################################################
  365. splash_settings = QSettings("Open Source", "FlatCAM")
  366. if splash_settings.contains("splash_screen"):
  367. show_splash = splash_settings.value("splash_screen")
  368. else:
  369. splash_settings.setValue('splash_screen', 1)
  370. # This will write the setting to the platform specific storage.
  371. del splash_settings
  372. show_splash = 1
  373. if show_splash and self.cmd_line_headless != 1:
  374. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  375. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  376. # self.splash.setMask(splash_pix.mask())
  377. # move splashscreen to the current monitor
  378. desktop = QtWidgets.QApplication.desktop()
  379. screen = desktop.screenNumber(QtGui.QCursor.pos())
  380. current_screen_center = desktop.availableGeometry(screen).center()
  381. self.splash.move(current_screen_center - self.splash.rect().center())
  382. self.splash.show()
  383. self.splash.showMessage(_("FlatCAM is initializing ..."),
  384. alignment=Qt.AlignBottom | Qt.AlignLeft,
  385. color=QtGui.QColor("gray"))
  386. else:
  387. show_splash = 0
  388. # ###########################################################################################################
  389. # ######################################### Initialize GUI ##################################################
  390. # ###########################################################################################################
  391. # FlatCAM colors used in plotting
  392. self.FC_light_green = '#BBF268BF'
  393. self.FC_dark_green = '#006E20BF'
  394. self.FC_light_blue = '#a5a5ffbf'
  395. self.FC_dark_blue = '#0000ffbf'
  396. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  397. if theme_settings.contains("theme"):
  398. theme = theme_settings.value('theme', type=str)
  399. else:
  400. theme = 'white'
  401. if self.defaults["global_cursor_color_enabled"]:
  402. self.cursor_color_3D = self.defaults["global_cursor_color"]
  403. else:
  404. if theme == 'white':
  405. self.cursor_color_3D = 'black'
  406. else:
  407. self.cursor_color_3D = 'gray'
  408. # update the defaults dict with the setting in QSetting
  409. self.defaults['global_theme'] = theme
  410. self.ui = MainGUI(self)
  411. # set FlatCAM units in the Status bar
  412. self.set_screen_units(self.defaults['units'])
  413. # ###########################################################################################################
  414. # ########################################### AUTOSAVE SETUP ################################################
  415. # ###########################################################################################################
  416. self.block_autosave = False
  417. self.autosave_timer = QtCore.QTimer(self)
  418. self.save_project_auto_update()
  419. self.autosave_timer.timeout.connect(self.save_project_auto)
  420. # ###########################################################################################################
  421. # #################################### LOAD PREPROCESSORS ###################################################
  422. # ###########################################################################################################
  423. # ----------------------------------------- WARNING --------------------------------------------------------
  424. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  425. # That's because the number of preprocessors can vary and here the comboboxes are populated
  426. # -----------------------------------------------------------------------------------------------------------
  427. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  428. # the preprocessor file
  429. self.preprocessors = load_preprocessors(self)
  430. # make sure that always the 'default' preprocessor is the first item in the dictionary
  431. if 'default' in self.preprocessors.keys():
  432. new_ppp_dict = {}
  433. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  434. default_pp = self.preprocessors.pop('default')
  435. new_ppp_dict['default'] = default_pp
  436. # then add the rest of the keys
  437. for name, val_class in self.preprocessors.items():
  438. new_ppp_dict[name] = val_class
  439. # and now put back the ordered dict with 'default' key first
  440. self.preprocessors = new_ppp_dict
  441. for name in list(self.preprocessors.keys()):
  442. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  443. if name.partition('_')[0] == 'Paste':
  444. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  445. continue
  446. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  447. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  448. if name == 'hpgl':
  449. continue
  450. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  451. # ###########################################################################################################
  452. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  453. # ###########################################################################################################
  454. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  455. inform=self.inform)
  456. self.preferencesUiManager.defaults_write_form()
  457. # When the self.defaults dictionary changes will update the Preferences GUI forms
  458. self.defaults.set_change_callback(self.on_defaults_dict_change)
  459. # ###########################################################################################################
  460. # ##################################### FIRST RUN SECTION ###################################################
  461. # ################################ It's done only once after install #####################################
  462. # ###########################################################################################################
  463. if self.defaults["first_run"] is True:
  464. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  465. initial_lay = 'minimal'
  466. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  467. # Set the combobox in Preferences to the current layout
  468. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  469. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  470. # after the first run, this object should be False
  471. self.defaults["first_run"] = False
  472. self.preferencesUiManager.save_defaults(silent=True)
  473. # ###########################################################################################################
  474. # ############################################ Data #########################################################
  475. # ###########################################################################################################
  476. self.recent = []
  477. self.recent_projects = []
  478. self.clipboard = QtWidgets.QApplication.clipboard()
  479. self.project_filename = None
  480. self.toggle_units_ignore = False
  481. # ###########################################################################################################
  482. # ########################################## LOAD LANGUAGES ################################################
  483. # ###########################################################################################################
  484. self.languages = fcTranslate.load_languages()
  485. for name in sorted(self.languages.values()):
  486. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  487. # ###########################################################################################################
  488. # ####################################### APPLY APP LANGUAGE ################################################
  489. # ###########################################################################################################
  490. ret_val = fcTranslate.apply_language('strings')
  491. if ret_val == "no language":
  492. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  493. log.debug("Could not find the Language files. The App strings are missing.")
  494. else:
  495. # make the current language the current selection on the language combobox
  496. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  497. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  498. # ###########################################################################################################
  499. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  500. # ###########################################################################################################
  501. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  502. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  503. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  504. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  505. self.defaults.propagate_defaults()
  506. # ###########################################################################################################
  507. # ######################################## UPDATE THE OPTIONS ###############################################
  508. # ###########################################################################################################
  509. self.options = LoudDict()
  510. # -----------------------------------------------------------------------------------------------------------
  511. # Update the self.options from the self.defaults
  512. # The self.defaults holds the application defaults while the self.options holds the object defaults
  513. # -----------------------------------------------------------------------------------------------------------
  514. # Copy app defaults to project options
  515. for def_key, def_val in self.defaults.items():
  516. self.options[def_key] = deepcopy(def_val)
  517. self.preferencesUiManager.show_preferences_gui()
  518. # ### End of Data ####
  519. # ###########################################################################################################
  520. # #################################### SETUP OBJECT COLLECTION ##############################################
  521. # ###########################################################################################################
  522. self.collection = ObjectCollection(app=self)
  523. self.ui.project_tab_layout.addWidget(self.collection.view)
  524. self.app_obj = AppObject(app=self)
  525. # ### Adjust tabs width ## ##
  526. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  527. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  528. self.collection.view.setMinimumWidth(290)
  529. self.log.debug("Finished creating Object Collection.")
  530. # ###########################################################################################################
  531. # ######################################## SETUP Plot Area ##################################################
  532. # ###########################################################################################################
  533. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  534. if self.defaults["global_graphic_engine"] == '3D':
  535. self.is_legacy = False
  536. else:
  537. self.is_legacy = True
  538. # Event signals disconnect id holders
  539. self.mp = None
  540. self.mm = None
  541. self.mr = None
  542. self.mdc = None
  543. self.mp_zc = None
  544. self.kp = None
  545. # Matplotlib axis
  546. self.axes = None
  547. if show_splash:
  548. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  549. "Canvas initialization started."),
  550. alignment=Qt.AlignBottom | Qt.AlignLeft,
  551. color=QtGui.QColor("gray"))
  552. start_plot_time = time.time() # debug
  553. self.plotcanvas = None
  554. self.app_cursor = None
  555. self.hover_shapes = None
  556. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  557. # setup the PlotCanvas
  558. self.on_plotcanvas_setup()
  559. end_plot_time = time.time()
  560. self.used_time = end_plot_time - start_plot_time
  561. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  562. if show_splash:
  563. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  564. "Canvas initialization started.\n"
  565. "Canvas initialization finished in"), '%.2f' % self.used_time),
  566. alignment=Qt.AlignBottom | Qt.AlignLeft,
  567. color=QtGui.QColor("gray"))
  568. self.ui.splitter.setStretchFactor(1, 2)
  569. # ###########################################################################################################
  570. # ############################################### SYS TRAY ##################################################
  571. # ###########################################################################################################
  572. if self.defaults["global_systray_icon"]:
  573. self.parent_w = QtWidgets.QWidget()
  574. if self.cmd_line_headless == 1:
  575. self.trayIcon = FlatCAMSystemTray(app=self,
  576. icon=QtGui.QIcon(self.resource_location +
  577. '/flatcam_icon32_green.png'),
  578. headless=True,
  579. parent=self.parent_w)
  580. else:
  581. self.trayIcon = FlatCAMSystemTray(app=self,
  582. icon=QtGui.QIcon(self.resource_location +
  583. '/flatcam_icon32_green.png'),
  584. parent=self.parent_w)
  585. # ###########################################################################################################
  586. # ############################################### Worker SETUP ##############################################
  587. # ###########################################################################################################
  588. if self.defaults["global_worker_number"]:
  589. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  590. else:
  591. self.workers = WorkerStack(workers_number=2)
  592. self.worker_task.connect(self.workers.add_task)
  593. self.log.debug("Finished creating Workers crew.")
  594. # ###########################################################################################################
  595. # ############################################# Activity Monitor ###########################################
  596. # ###########################################################################################################
  597. self.activity_view = FlatCAMActivityView(app=self)
  598. self.ui.infobar.addWidget(self.activity_view)
  599. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  600. # ###########################################################################################################
  601. # ############################################# Signal handling #############################################
  602. # ###########################################################################################################
  603. # ########################################## Custom signals ################################################
  604. # signal for displaying messages in status bar
  605. self.inform.connect(self.info)
  606. # signal to be called when the app is quiting
  607. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  608. self.message.connect(lambda: message_dialog(parent=self.ui))
  609. # self.progress.connect(self.set_progress_bar)
  610. # signals emitted when file state change
  611. self.file_opened.connect(self.register_recent)
  612. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  613. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  614. # ########################################## Standard signals ###############################################
  615. # ### Menu
  616. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  617. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  618. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  619. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  620. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  621. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  622. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  623. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  624. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  625. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  626. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  627. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  628. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  629. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  630. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  631. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  632. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  633. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  634. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  635. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  636. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  637. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  638. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  639. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  640. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  641. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  642. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  643. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  644. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  645. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  646. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  647. self.ui.menufile_exit.triggered.connect(self.final_save)
  648. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  649. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  650. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  651. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  652. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  653. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  654. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  655. self.ui.menueditdelete.triggered.connect(self.on_delete)
  656. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  657. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  658. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  659. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  660. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  661. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  662. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  663. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  664. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  665. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  666. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  667. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  668. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  669. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  670. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  671. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  672. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  673. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  674. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  675. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  676. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  677. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  678. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  679. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  680. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  681. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  682. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  683. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  684. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  685. self.ui.menuview_replot.triggered.connect(self.plot_all)
  686. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  687. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  688. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  689. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  690. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  691. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  692. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  693. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  694. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  695. self.ui.menuview_toggle_hud.triggered.connect(self.on_toggle_hud)
  696. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  697. self.ui.menuhelp_about.triggered.connect(self.on_about)
  698. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  699. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  700. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  701. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  702. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  703. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  704. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  705. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  706. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  707. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  708. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  709. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  710. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  711. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  712. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  713. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  714. # ToolBar signals
  715. self.connect_toolbar_signals()
  716. # Notebook and Plot Tab Area signals
  717. # make the right click on the notebook tab and plot tab area tab raise a menu
  718. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  719. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  720. self.on_tab_setup_context_menu()
  721. # activate initial state
  722. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  723. # Context Menu
  724. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  725. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  726. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  727. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  728. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  729. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  730. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  731. self.ui.clearplot.triggered.connect(self.clear_plots)
  732. self.ui.replot.triggered.connect(self.plot_all)
  733. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  734. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  735. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  736. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  737. self.ui.popmenu_move.triggered.connect(self.obj_move)
  738. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  739. # Project Context Menu -> Color Setting
  740. for act in self.ui.menuprojectcolor.actions():
  741. act.triggered.connect(self.on_set_color_action_triggered)
  742. # ###########################################################################################################
  743. # #################################### GUI PREFERENCES SIGNALS ##############################################
  744. # ###########################################################################################################
  745. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  746. lambda: self.on_toggle_units(no_pref=False))
  747. # ##################################### Workspace Setting Signals ###########################################
  748. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  749. self.on_workspace_modified)
  750. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  751. self.on_workspace_modified
  752. )
  753. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  754. # ###########################################################################################################
  755. # ######################################## GUI SETTINGS SIGNALS #############################################
  756. # ###########################################################################################################
  757. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  758. # ######################################## Tools related signals ############################################
  759. # portability changed signal
  760. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  761. # Object list
  762. self.object_status_changed.connect(self.collection.on_collection_updated)
  763. # when there are arguments at application startup this get launched
  764. self.args_at_startup[list].connect(self.on_startup_args)
  765. # ###########################################################################################################
  766. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  767. # ###########################################################################################################
  768. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  769. lambda: self.restore_extensions(ext_type='excellon'))
  770. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  771. lambda: self.restore_extensions(ext_type='gcode'))
  772. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  773. lambda: self.restore_extensions(ext_type='gerber'))
  774. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  775. lambda: self.delete_all_extensions(ext_type='excellon'))
  776. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  777. lambda: self.delete_all_extensions(ext_type='gcode'))
  778. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  779. lambda: self.delete_all_extensions(ext_type='gerber'))
  780. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  781. lambda: self.add_extension(ext_type='excellon'))
  782. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  783. lambda: self.add_extension(ext_type='gcode'))
  784. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  785. lambda: self.add_extension(ext_type='gerber'))
  786. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  787. lambda: self.del_extension(ext_type='excellon'))
  788. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  789. lambda: self.del_extension(ext_type='gcode'))
  790. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  791. lambda: self.del_extension(ext_type='gerber'))
  792. # connect the 'Apply' buttons from the Preferences/File Associations
  793. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  794. lambda: self.on_register_files(obj_type='excellon'))
  795. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  796. lambda: self.on_register_files(obj_type='gcode'))
  797. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  798. lambda: self.on_register_files(obj_type='gerber'))
  799. # ###########################################################################################################
  800. # ########################################### KEYWORDS SIGNALS ##############################################
  801. # ###########################################################################################################
  802. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  803. lambda: self.restore_extensions(ext_type='keyword'))
  804. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  805. lambda: self.delete_all_extensions(ext_type='keyword'))
  806. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  807. lambda: self.add_extension(ext_type='keyword'))
  808. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  809. lambda: self.del_extension(ext_type='keyword'))
  810. # connect the abort_all_tasks related slots to the related signals
  811. self.proc_container.idle_flag.connect(self.app_is_idle)
  812. # signal emitted when a tab is closed in the Plot Area
  813. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  814. # signal to close the application
  815. self.close_app_signal.connect(self.kill_app)
  816. # ################################# FINISHED CONNECTING SIGNALS #############################################
  817. # ###########################################################################################################
  818. # ###########################################################################################################
  819. # ###########################################################################################################
  820. self.log.debug("Finished connecting Signals.")
  821. # ###########################################################################################################
  822. # ########################################## Other setups ###################################################
  823. # ###########################################################################################################
  824. # to use for tools like Distance tool who depends on the event sources who are changed inside the AppEditors
  825. # depending on from where those tools are called different actions can be done
  826. self.call_source = 'app'
  827. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  828. self.tool_tab_locked = False
  829. # decide if to show or hide the Notebook side of the screen at startup
  830. if self.defaults["global_project_at_startup"] is True:
  831. self.ui.splitter.setSizes([1, 1])
  832. else:
  833. self.ui.splitter.setSizes([0, 1])
  834. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  835. self.setup_component_editor()
  836. # ###########################################################################################################
  837. # ####################################### Auto-complete KEYWORDS ############################################
  838. # ###########################################################################################################
  839. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  840. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  841. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  842. 'export_exc',
  843. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  844. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  845. 'interiors', 'isolate', 'join_excellon',
  846. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  847. 'mirror', 'ncc',
  848. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  849. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  850. 'options', 'origin',
  851. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  852. 'save', 'save_project',
  853. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  854. 'skew', 'subtract_poly', 'subtract_rectangle',
  855. 'version', 'write_gcode'
  856. ]
  857. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  858. 'Paste_1',
  859. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  860. 'Toolchange_manual', 'True', 'Users',
  861. 'all', 'auto', 'axis',
  862. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  863. 'contour', 'default',
  864. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  865. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  866. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  867. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  868. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  869. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  870. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  871. 'spacing_columns',
  872. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  873. 'toolchange_xy', 'toolchangez', 'travelz',
  874. 'tooldia', 'use_threads', 'value',
  875. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  876. ]
  877. self.tcl_keywords = [
  878. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  879. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  880. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  881. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  882. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  883. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  884. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  885. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  886. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  887. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  888. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  889. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  890. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  891. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  892. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  893. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  894. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  895. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  896. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  897. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  898. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  899. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  900. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  901. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  902. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  903. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  904. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  905. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  906. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  907. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  908. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  909. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  910. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  911. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  912. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  913. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  914. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  915. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  916. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  917. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  918. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  919. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  920. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  921. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  922. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  923. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  924. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  925. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  926. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  927. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  928. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  929. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  930. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  931. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  932. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  933. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  934. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  935. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  936. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  937. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  938. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  939. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  940. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  941. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  942. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  943. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  944. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  945. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  946. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  947. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  948. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  949. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  950. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  951. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  952. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  953. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  954. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  955. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  956. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  957. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  958. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  959. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  960. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  961. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  962. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  963. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  964. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  965. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  966. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  967. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  968. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  969. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  970. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  971. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  972. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  973. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  974. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  975. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  976. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  977. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  978. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  979. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  980. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  981. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  982. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  983. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  984. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  985. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  986. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  987. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  988. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  989. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  990. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  991. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  992. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  993. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  994. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  995. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  996. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  997. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  998. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  999. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1000. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1001. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1002. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1003. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1004. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1005. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1006. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1007. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1008. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1009. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1010. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1011. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1012. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1013. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1014. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1015. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1016. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1017. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1018. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1019. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1020. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1021. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1022. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1023. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1024. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1025. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1026. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1027. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1028. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1029. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1030. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1031. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1032. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1033. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1034. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1035. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1036. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1037. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1038. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1039. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1040. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1041. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1042. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1043. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1044. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1045. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1046. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1047. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1048. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1049. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1050. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1051. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1052. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1053. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1054. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1055. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1056. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1057. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1058. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1059. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1060. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1061. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1062. ]
  1063. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1064. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1065. # ###########################################################################################################
  1066. # ############################################## Shell SETUP ################################################
  1067. # ###########################################################################################################
  1068. self.shell = FCShell(app=self, version=self.version)
  1069. self.ui.shell_dock.setWidget(self.shell)
  1070. self.log.debug("TCL Shell has been initialized.")
  1071. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1072. if self.defaults["global_shell_at_startup"]:
  1073. self.ui.shell_dock.show()
  1074. else:
  1075. self.ui.shell_dock.hide()
  1076. # ###########################################################################################################
  1077. # ########################################## Tools and Plugins ##############################################
  1078. # ###########################################################################################################
  1079. self.dblsidedtool = None
  1080. self.distance_tool = None
  1081. self.distance_min_tool = None
  1082. self.panelize_tool = None
  1083. self.film_tool = None
  1084. self.paste_tool = None
  1085. self.calculator_tool = None
  1086. self.rules_tool = None
  1087. self.sub_tool = None
  1088. self.move_tool = None
  1089. self.cutout_tool = None
  1090. self.ncclear_tool = None
  1091. self.paint_tool = None
  1092. self.isolation_tool = None
  1093. self.optimal_tool = None
  1094. self.transform_tool = None
  1095. self.properties_tool = None
  1096. self.pdf_tool = None
  1097. self.image_tool = None
  1098. self.pcb_wizard_tool = None
  1099. self.cal_exc_tool = None
  1100. self.qrcode_tool = None
  1101. self.copper_thieving_tool = None
  1102. self.fiducial_tool = None
  1103. self.edrills_tool = None
  1104. self.align_objects_tool = None
  1105. self.punch_tool = None
  1106. self.invert_tool = None
  1107. self.corners_tool = None
  1108. self.etch_tool = None
  1109. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1110. try:
  1111. self.install_tools()
  1112. except AttributeError as e:
  1113. log.debug("App.__init__() install tools() --> %s" % str(e))
  1114. # ###########################################################################################################
  1115. # ############################################ SETUP RECENT ITEMS ###########################################
  1116. # ###########################################################################################################
  1117. self.setup_recent_items()
  1118. # ###########################################################################################################
  1119. # ######################################### BookMarks Manager ###############################################
  1120. # ###########################################################################################################
  1121. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1122. self.install_bookmarks()
  1123. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1124. # ###########################################################################################################
  1125. # ########################################### Tools Database ################################################
  1126. # ###########################################################################################################
  1127. self.tools_db_tab = None
  1128. # ### System Font Parsing ###
  1129. # self.f_parse = ParseFont(self)
  1130. # self.parse_system_fonts()
  1131. # ###########################################################################################################
  1132. # ######################################### Check for updates ###############################################
  1133. # ###########################################################################################################
  1134. # Separate thread (Not worker)
  1135. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1136. if (self.beta is False or self.beta is None) and \
  1137. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1138. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1139. # self.thr2 = QtCore.QThread()
  1140. self.worker_task.emit({'fcn': self.version_check,
  1141. 'params': []})
  1142. # self.thr2.start(QtCore.QThread.LowPriority)
  1143. # ###########################################################################################################
  1144. # ##################################### Register files with FlatCAM; #######################################
  1145. # ################################### It works only for Windows for now ####################################
  1146. # ###########################################################################################################
  1147. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1148. self.on_register_files()
  1149. # ###########################################################################################################
  1150. # ######################################## Variables for global usage #######################################
  1151. # ###########################################################################################################
  1152. # hold the App units
  1153. self.units = 'MM'
  1154. # coordinates for relative position display
  1155. self.rel_point1 = (0, 0)
  1156. self.rel_point2 = (0, 0)
  1157. # variable to store coordinates
  1158. self.pos = (0, 0)
  1159. self.pos_canvas = (0, 0)
  1160. self.pos_jump = (0, 0)
  1161. # variable to store mouse coordinates
  1162. self.mouse = [0, 0]
  1163. # variable to store the delta positions on cavnas
  1164. self.dx = 0
  1165. self.dy = 0
  1166. # decide if we have a double click or single click
  1167. self.doubleclick = False
  1168. # store here the is_dragging value
  1169. self.event_is_dragging = False
  1170. # variable to store if a command is active (then the var is not None) and which one it is
  1171. self.command_active = None
  1172. # variable to store the status of moving selection action
  1173. # None value means that it's not an selection action
  1174. # True value = a selection from left to right
  1175. # False value = a selection from right to left
  1176. self.selection_type = None
  1177. # List to store the objects that are currently loaded in FlatCAM
  1178. # This list is updated on each object creation or object delete
  1179. self.all_objects_list = []
  1180. self.objects_under_the_click_list = []
  1181. # List to store the objects that are selected
  1182. self.sel_objects_list = []
  1183. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1184. self.key_modifiers = None
  1185. # Variable to hold the status of the axis
  1186. self.toggle_axis = True
  1187. # Variable to hold the status of the grid lines
  1188. self.toggle_grid_lines = True
  1189. # Variable to store the status of the code editor
  1190. self.toggle_codeeditor = False
  1191. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1192. self.click_noproject = False
  1193. self.cursor = None
  1194. # Variable to store the GCODE that was edited
  1195. self.gcode_edited = ""
  1196. self.text_editor_tab = None
  1197. # reference for the self.ui.code_editor
  1198. self.reference_code_editor = None
  1199. self.script_code = ''
  1200. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1201. self.tools_db_changed_flag = False
  1202. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1203. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1204. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1205. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1206. 'tsm']
  1207. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1208. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1209. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1210. 'sbp', 'tap', 'xpi']
  1211. self.svg_list = ['svg']
  1212. self.dxf_list = ['dxf']
  1213. self.pdf_list = ['pdf']
  1214. self.prj_list = ['flatprj']
  1215. self.conf_list = ['flatconfig']
  1216. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1217. # flag for polygons not cleared
  1218. self.poly_not_cleared = False
  1219. # VisPy visuals
  1220. self.isHovering = False
  1221. self.notHovering = True
  1222. # Window geometry
  1223. self.x_pos = None
  1224. self.y_pos = None
  1225. self.width = None
  1226. self.height = None
  1227. # when True, the app has to return from any thread
  1228. self.abort_flag = False
  1229. # set the value used in the Windows Title
  1230. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1231. # this holds a widget that is installed in the Plot Area when View Source option is used
  1232. self.source_editor_tab = None
  1233. self.pagesize = {}
  1234. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1235. # VisPy visuals
  1236. if self.is_legacy is False:
  1237. try:
  1238. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1239. except AttributeError:
  1240. self.tool_shapes = None
  1241. else:
  1242. from AppGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1243. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1244. # used in the delayed shutdown self.start_delayed_quit() method
  1245. self.save_timer = None
  1246. # ###########################################################################################################
  1247. # ################################## ADDING FlatCAM EDITORS section #########################################
  1248. # ###########################################################################################################
  1249. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1250. # at the first launch of the App , the editors will not be functional.
  1251. try:
  1252. self.geo_editor = FlatCAMGeoEditor(self)
  1253. except AttributeError:
  1254. pass
  1255. try:
  1256. self.exc_editor = FlatCAMExcEditor(self)
  1257. except AttributeError:
  1258. pass
  1259. try:
  1260. self.grb_editor = FlatCAMGrbEditor(self)
  1261. except AttributeError:
  1262. pass
  1263. self.log.debug("Finished adding FlatCAM Editor's.")
  1264. self.set_ui_title(name=_("New Project - Not saved"))
  1265. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1266. current_platform = platform.architecture()[0]
  1267. if current_platform != '64bit':
  1268. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1269. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1270. # ###########################################################################################################
  1271. # ########################################### EXCLUSION AREAS ###############################################
  1272. # ###########################################################################################################
  1273. self.exc_areas = ExclusionAreas(app=self)
  1274. # ###########################################################################################################
  1275. # ##################################### Finished the CONSTRUCTOR ############################################
  1276. # ###########################################################################################################
  1277. App.log.debug("END of constructor. Releasing control.")
  1278. # ###########################################################################################################
  1279. # ########################################## SHOW GUI #######################################################
  1280. # ###########################################################################################################
  1281. # if the app is not started as headless, show it
  1282. if self.cmd_line_headless != 1:
  1283. if show_splash:
  1284. # finish the splash
  1285. self.splash.finish(self.ui)
  1286. mgui_settings = QSettings("Open Source", "FlatCAM")
  1287. if mgui_settings.contains("maximized_gui"):
  1288. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1289. if maximized_ui is True:
  1290. self.ui.showMaximized()
  1291. else:
  1292. self.ui.show()
  1293. else:
  1294. self.ui.show()
  1295. if self.defaults["global_systray_icon"]:
  1296. self.trayIcon.show()
  1297. else:
  1298. log.warning("******************* RUNNING HEADLESS *******************")
  1299. # ###########################################################################################################
  1300. # ######################################## START-UP ARGUMENTS ###############################################
  1301. # ###########################################################################################################
  1302. # test if the program was started with a script as parameter
  1303. if self.cmd_line_shellvar:
  1304. try:
  1305. cnt = 0
  1306. command_tcl = 0
  1307. for i in self.cmd_line_shellvar.split(','):
  1308. if i is not None:
  1309. # noinspection PyBroadException
  1310. try:
  1311. command_tcl = eval(i)
  1312. except Exception:
  1313. command_tcl = i
  1314. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1315. cnt += 1
  1316. # if there are Windows paths then replace the path separator with a Unix like one
  1317. if sys.platform == 'win32':
  1318. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1319. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1320. except Exception as ext:
  1321. print("ERROR: ", ext)
  1322. sys.exit(2)
  1323. if self.cmd_line_shellfile:
  1324. if self.cmd_line_headless != 1:
  1325. if self.ui.shell_dock.isHidden():
  1326. self.ui.shell_dock.show()
  1327. try:
  1328. with open(self.cmd_line_shellfile, "r") as myfile:
  1329. # if show_splash:
  1330. # self.splash.showMessage('%s: %ssec\n%s' % (
  1331. # _("Canvas initialization started.\n"
  1332. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1333. # _("Executing Tcl Script ...")),
  1334. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1335. # color=QtGui.QColor("gray"))
  1336. cmd_line_shellfile_text = myfile.read()
  1337. if self.cmd_line_headless != 1:
  1338. self.shell.exec_command(cmd_line_shellfile_text)
  1339. else:
  1340. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1341. except Exception as ext:
  1342. print("ERROR: ", ext)
  1343. sys.exit(2)
  1344. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1345. # the path/file_name must be enclosed in quotes if it contain spaces
  1346. if App.args:
  1347. self.args_at_startup.emit(App.args)
  1348. if self.defaults.old_defaults_found is True:
  1349. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1350. "Please reboot the application to update."))
  1351. self.defaults.old_defaults_found = False
  1352. # ######################################### INIT FINISHED #######################################################
  1353. # #################################################################################################################
  1354. # #################################################################################################################
  1355. # #################################################################################################################
  1356. # #################################################################################################################
  1357. # #################################################################################################################
  1358. @staticmethod
  1359. def copy_and_overwrite(from_path, to_path):
  1360. """
  1361. From here:
  1362. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1363. :param from_path: source path
  1364. :param to_path: destination path
  1365. :return: None
  1366. """
  1367. if os.path.exists(to_path):
  1368. shutil.rmtree(to_path)
  1369. try:
  1370. shutil.copytree(from_path, to_path)
  1371. except FileNotFoundError:
  1372. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\AppGUI\\VisPyData\\data'
  1373. shutil.copytree(from_new_path, to_path)
  1374. def on_startup_args(self, args, silent=False):
  1375. """
  1376. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1377. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1378. :param args: a list containing the application args at startup
  1379. :return: None
  1380. """
  1381. if args is not None:
  1382. args_to_process = args
  1383. else:
  1384. args_to_process = App.args
  1385. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1386. for argument in args_to_process:
  1387. if '.FlatPrj'.lower() in argument.lower():
  1388. try:
  1389. project_name = str(argument)
  1390. if project_name == "":
  1391. if silent is False:
  1392. self.inform.emit(_("Cancelled."))
  1393. else:
  1394. # self.open_project(project_name)
  1395. run_from_arg = True
  1396. # self.worker_task.emit({'fcn': self.open_project,
  1397. # 'params': [project_name, run_from_arg]})
  1398. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1399. except Exception as e:
  1400. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1401. elif '.FlatConfig'.lower() in argument.lower():
  1402. try:
  1403. file_name = str(argument)
  1404. if file_name == "":
  1405. if silent is False:
  1406. self.inform.emit(_("Open Config file failed."))
  1407. else:
  1408. run_from_arg = True
  1409. # self.worker_task.emit({'fcn': self.open_config_file,
  1410. # 'params': [file_name, run_from_arg]})
  1411. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1412. except Exception as e:
  1413. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1414. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1415. try:
  1416. file_name = str(argument)
  1417. if file_name == "":
  1418. if silent is False:
  1419. self.inform.emit(_("Open Script file failed."))
  1420. else:
  1421. if silent is False:
  1422. self.on_fileopenscript(name=file_name)
  1423. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1424. self.on_filerunscript(name=file_name)
  1425. except Exception as e:
  1426. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1427. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1428. log.debug("App.on_startup_args() --> Quit event.")
  1429. sys.exit()
  1430. elif 'save'.lower() in argument.lower():
  1431. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1432. self.preferencesUiManager.save_defaults()
  1433. else:
  1434. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1435. proc_arg = argument.lower()
  1436. for ext in exc_list:
  1437. proc_ext = ext.replace(' ', '')
  1438. proc_ext = '.%s' % proc_ext
  1439. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1440. file_name = str(argument)
  1441. if file_name == "":
  1442. if silent is False:
  1443. self.inform.emit(_("Open Excellon file failed."))
  1444. else:
  1445. self.on_fileopenexcellon(name=file_name, signal=None)
  1446. return
  1447. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1448. for ext in gco_list:
  1449. proc_ext = ext.replace(' ', '')
  1450. proc_ext = '.%s' % proc_ext
  1451. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1452. file_name = str(argument)
  1453. if file_name == "":
  1454. if silent is False:
  1455. self.inform.emit(_("Open GCode file failed."))
  1456. else:
  1457. self.on_fileopengcode(name=file_name, signal=None)
  1458. return
  1459. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1460. for ext in grb_list:
  1461. proc_ext = ext.replace(' ', '')
  1462. proc_ext = '.%s' % proc_ext
  1463. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1464. file_name = str(argument)
  1465. if file_name == "":
  1466. if silent is False:
  1467. self.inform.emit(_("Open Gerber file failed."))
  1468. else:
  1469. self.on_fileopengerber(name=file_name, signal=None)
  1470. return
  1471. # if it reached here without already returning then the app was registered with a file that it does not
  1472. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1473. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1474. # for arg in args_to_process:
  1475. # if 'FlatCAM.exe' in arg:
  1476. # continue
  1477. # else:
  1478. # sys.exit(2)
  1479. def set_ui_title(self, name):
  1480. """
  1481. Sets the title of the main window.
  1482. :param name: String that store the project path and project name
  1483. :return: None
  1484. """
  1485. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1486. (self.version,
  1487. ('BETA' if self.beta else ''),
  1488. platform.architecture()[0],
  1489. self.engine,
  1490. name)
  1491. )
  1492. def on_app_restart(self):
  1493. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1494. # be left in the SySTray
  1495. try:
  1496. self.trayIcon.hide()
  1497. except Exception:
  1498. pass
  1499. fcTranslate.restart_program(app=self)
  1500. def clear_pool(self):
  1501. """
  1502. Clear the multiprocessing pool and calls garbage collector.
  1503. :return: None
  1504. """
  1505. self.pool.close()
  1506. self.pool = Pool()
  1507. self.pool_recreated.emit(self.pool)
  1508. gc.collect()
  1509. def install_tools(self):
  1510. """
  1511. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1512. Instantiation of the Tools classes.
  1513. The order that the tools are installed is important as they can depend on each other install position.
  1514. :return: None
  1515. """
  1516. self.distance_tool = Distance(self)
  1517. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1518. before=self.ui.menueditorigin,
  1519. separator=False)
  1520. self.distance_min_tool = DistanceMin(self)
  1521. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1522. pos=self.ui.menuedit,
  1523. before=self.ui.menueditorigin,
  1524. separator=True)
  1525. self.dblsidedtool = DblSidedTool(self)
  1526. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1527. self.cal_exc_tool = ToolCalibration(self)
  1528. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1529. before=self.dblsidedtool.menuAction,
  1530. separator=False)
  1531. self.align_objects_tool = AlignObjects(self)
  1532. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1533. self.edrills_tool = ToolExtractDrills(self)
  1534. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1535. self.panelize_tool = Panelize(self)
  1536. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1537. self.film_tool = Film(self)
  1538. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1539. self.paste_tool = SolderPaste(self)
  1540. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1541. self.calculator_tool = ToolCalculator(self)
  1542. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1543. self.sub_tool = ToolSub(self)
  1544. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1545. pos=self.ui.menutool, separator=True)
  1546. self.rules_tool = RulesCheck(self)
  1547. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1548. pos=self.ui.menutool, separator=False)
  1549. self.optimal_tool = ToolOptimal(self)
  1550. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1551. pos=self.ui.menutool, separator=True)
  1552. self.move_tool = ToolMove(self)
  1553. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1554. before=self.ui.menueditorigin, separator=True)
  1555. self.cutout_tool = CutOut(self)
  1556. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1557. before=self.sub_tool.menuAction)
  1558. self.ncclear_tool = NonCopperClear(self)
  1559. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1560. before=self.sub_tool.menuAction, separator=True)
  1561. self.paint_tool = ToolPaint(self)
  1562. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1563. before=self.sub_tool.menuAction, separator=True)
  1564. self.isolation_tool = ToolIsolation(self)
  1565. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1566. before=self.sub_tool.menuAction, separator=True)
  1567. self.copper_thieving_tool = ToolCopperThieving(self)
  1568. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1569. pos=self.ui.menutool)
  1570. self.fiducial_tool = ToolFiducials(self)
  1571. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1572. pos=self.ui.menutool)
  1573. self.qrcode_tool = QRCode(self)
  1574. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1575. pos=self.ui.menutool)
  1576. self.punch_tool = ToolPunchGerber(self)
  1577. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1578. self.invert_tool = ToolInvertGerber(self)
  1579. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1580. self.corners_tool = ToolCorners(self)
  1581. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1582. self.etch_tool = ToolEtchCompensation(self)
  1583. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1584. self.transform_tool = ToolTransform(self)
  1585. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1586. pos=self.ui.menuoptions, separator=True)
  1587. self.properties_tool = Properties(self)
  1588. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1589. pos=self.ui.menuoptions)
  1590. self.pdf_tool = ToolPDF(self)
  1591. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1592. pos=self.ui.menufileimport,
  1593. separator=True)
  1594. self.image_tool = ToolImage(self)
  1595. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1596. pos=self.ui.menufileimport,
  1597. separator=True)
  1598. self.pcb_wizard_tool = PcbWizard(self)
  1599. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1600. pos=self.ui.menufileimport)
  1601. self.log.debug("Tools are installed.")
  1602. def remove_tools(self):
  1603. """
  1604. Will remove all the actions in the Tool menu.
  1605. :return: None
  1606. """
  1607. for act in self.ui.menutool.actions():
  1608. self.ui.menutool.removeAction(act)
  1609. def init_tools(self):
  1610. """
  1611. Initialize the Tool tab in the notebook side of the central widget.
  1612. Remove the actions in the Tools menu.
  1613. Instantiate again the FlatCAM tools (plugins).
  1614. All this is required when changing the layout: standard, compact etc.
  1615. :return: None
  1616. """
  1617. log.debug("init_tools()")
  1618. # delete the data currently in the Tools Tab and the Tab itself
  1619. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1620. if widget is not None:
  1621. widget.deleteLater()
  1622. self.ui.notebook.removeTab(2)
  1623. # rebuild the Tools Tab
  1624. self.ui.tool_tab = QtWidgets.QWidget()
  1625. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1626. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1627. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1628. self.ui.tool_scroll_area = VerticalScrollArea()
  1629. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1630. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1631. # first remove all of them
  1632. self.remove_tools()
  1633. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1634. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1635. '&Command Line\tS')
  1636. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1637. # third install all of them
  1638. try:
  1639. self.install_tools()
  1640. except AttributeError:
  1641. pass
  1642. self.log.debug("Tools are initialized.")
  1643. # def parse_system_fonts(self):
  1644. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1645. # 'params': []})
  1646. def connect_toolbar_signals(self):
  1647. """
  1648. Reconnect the signals to the actions in the toolbar.
  1649. This has to be done each time after the FlatCAM tools are removed/installed.
  1650. :return: None
  1651. """
  1652. # Toolbar
  1653. # File Toolbar Signals
  1654. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1655. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1656. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1657. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1658. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1659. # View Toolbar Signals
  1660. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1661. self.ui.replot_btn.triggered.connect(self.plot_all)
  1662. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1663. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1664. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1665. # Edit Toolbar Signals
  1666. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1667. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1668. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1669. self.ui.delete_btn.triggered.connect(self.on_delete)
  1670. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1671. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1672. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1673. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1674. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1675. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1676. # Scripting Toolbar Signals
  1677. self.ui.shell_btn.triggered.connect(self.ui.toggle_shell_ui)
  1678. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1679. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1680. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1681. # Tools Toolbar Signals
  1682. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1683. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1684. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1685. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1686. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1687. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1688. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1689. self.ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1690. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1691. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1692. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1693. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1694. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1695. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1696. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1697. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1698. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1699. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1700. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1701. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1702. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1703. self.ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1704. self.ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1705. def object2editor(self):
  1706. """
  1707. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1708. :return: None
  1709. """
  1710. self.defaults.report_usage("object2editor()")
  1711. # disable the objects menu as it may interfere with the AppEditors
  1712. self.ui.menuobjects.setDisabled(True)
  1713. edited_object = self.collection.get_active()
  1714. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1715. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1716. pass
  1717. else:
  1718. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1719. return
  1720. if isinstance(edited_object, GeometryObject):
  1721. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1722. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1723. # we set the notebook to hidden
  1724. # self.ui.splitter.setSizes([0, 1])
  1725. if edited_object.multigeo is True:
  1726. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1727. if len(sel_rows) > 1:
  1728. self.inform.emit('[WARNING_NOTCL] %s' %
  1729. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1730. "is not possible.\n"
  1731. "Edit only one geometry at a time."))
  1732. # determine the tool dia of the selected tool
  1733. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1734. # now find the key in the edited_object.tools that has this tooldia
  1735. multi_tool = 1
  1736. for tool in edited_object.tools:
  1737. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1738. multi_tool = tool
  1739. break
  1740. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1741. else:
  1742. self.geo_editor.edit_fcgeometry(edited_object)
  1743. # set call source to the Editor we go into
  1744. self.call_source = 'geo_editor'
  1745. elif isinstance(edited_object, ExcellonObject):
  1746. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1747. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1748. if self.ui.splitter.sizes()[0] == 0:
  1749. self.ui.splitter.setSizes([1, 1])
  1750. self.exc_editor.edit_fcexcellon(edited_object)
  1751. # set call source to the Editor we go into
  1752. self.call_source = 'exc_editor'
  1753. elif isinstance(edited_object, GerberObject):
  1754. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1755. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1756. if self.ui.splitter.sizes()[0] == 0:
  1757. self.ui.splitter.setSizes([1, 1])
  1758. self.grb_editor.edit_fcgerber(edited_object)
  1759. # set call source to the Editor we go into
  1760. self.call_source = 'grb_editor'
  1761. # reset the following variables so the UI is built again after edit
  1762. edited_object.ui_build = False
  1763. edited_object.build_aperture_storage = False
  1764. elif isinstance(edited_object, CNCJobObject):
  1765. if self.ui.splitter.sizes()[0] == 0:
  1766. self.ui.splitter.setSizes([1, 1])
  1767. edited_object.on_edit_code_click()
  1768. return
  1769. # make sure that we can't select another object while in Editor Mode:
  1770. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1771. self.ui.project_frame.setDisabled(True)
  1772. # delete any selection shape that might be active as they are not relevant in Editor
  1773. self.delete_selection_shape()
  1774. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1775. self.ui.plot_tab_area.protectTab(0)
  1776. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1777. self.should_we_save = True
  1778. def editor2object(self, cleanup=None):
  1779. """
  1780. Transfers the Geometry or Excellon from it's editor to the current object.
  1781. :return: None
  1782. """
  1783. self.defaults.report_usage("editor2object()")
  1784. # re-enable the objects menu that was disabled on entry in Editor mode
  1785. self.ui.menuobjects.setDisabled(False)
  1786. # do not update a geometry or excellon object unless it comes out of an editor
  1787. if self.call_source != 'app':
  1788. edited_obj = self.collection.get_active()
  1789. if cleanup is None:
  1790. msgbox = QtWidgets.QMessageBox()
  1791. msgbox.setText(_("Do you want to save the edited object?"))
  1792. msgbox.setWindowTitle(_("Close Editor"))
  1793. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1794. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1795. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1796. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1797. msgbox.setDefaultButton(bt_yes)
  1798. msgbox.exec_()
  1799. response = msgbox.clickedButton()
  1800. if response == bt_yes:
  1801. # clean the Tools Tab
  1802. self.ui.tool_scroll_area.takeWidget()
  1803. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1804. self.ui.notebook.setTabText(2, "Tool")
  1805. if isinstance(edited_obj, GeometryObject):
  1806. obj_type = "Geometry"
  1807. self.geo_editor.update_fcgeometry(edited_obj)
  1808. # self.geo_editor.update_options(edited_obj)
  1809. # restore GUI to the Selected TAB
  1810. # Remove anything else in the AppGUI
  1811. self.ui.tool_scroll_area.takeWidget()
  1812. # update the geo object options so it is including the bounding box values
  1813. try:
  1814. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1815. edited_obj.options['xmin'] = xmin
  1816. edited_obj.options['ymin'] = ymin
  1817. edited_obj.options['xmax'] = xmax
  1818. edited_obj.options['ymax'] = ymax
  1819. except AttributeError as e:
  1820. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1821. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1822. edited_obj.build_ui()
  1823. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1824. elif isinstance(edited_obj, GerberObject):
  1825. obj_type = "Gerber"
  1826. self.grb_editor.update_fcgerber()
  1827. # self.grb_editor.update_options(edited_obj)
  1828. # delete the old object (the source object) if it was an empty one
  1829. try:
  1830. if len(edited_obj.solid_geometry) == 0:
  1831. old_name = edited_obj.options['name']
  1832. self.collection.delete_by_name(old_name)
  1833. except TypeError:
  1834. # if the solid_geometry is a single Polygon the len() will not work
  1835. # in any case, falling here means that we have something in the solid_geometry, even if only
  1836. # a single Polygon, therefore we pass this
  1837. pass
  1838. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1839. # restore GUI to the Selected TAB
  1840. # Remove anything else in the AppGUI
  1841. self.ui.selected_scroll_area.takeWidget()
  1842. elif isinstance(edited_obj, ExcellonObject):
  1843. obj_type = "Excellon"
  1844. self.exc_editor.update_fcexcellon(edited_obj)
  1845. # self.exc_editor.update_options(edited_obj)
  1846. # restore GUI to the Selected TAB
  1847. # Remove anything else in the AppGUI
  1848. self.ui.tool_scroll_area.takeWidget()
  1849. # delete the old object (the source object) if it was an empty one
  1850. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1851. old_name = edited_obj.options['name']
  1852. self.collection.delete_by_name(name=old_name)
  1853. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1854. else:
  1855. self.inform.emit('[WARNING_NOTCL] %s' %
  1856. _("Select a Gerber, Geometry or Excellon Object to update."))
  1857. return
  1858. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1859. elif response == bt_no:
  1860. # clean the Tools Tab
  1861. self.ui.tool_scroll_area.takeWidget()
  1862. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1863. self.ui.notebook.setTabText(2, "Tool")
  1864. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1865. if isinstance(edited_obj, GeometryObject):
  1866. self.geo_editor.deactivate()
  1867. edited_obj.build_ui()
  1868. elif isinstance(edited_obj, GerberObject):
  1869. self.grb_editor.deactivate_grb_editor()
  1870. edited_obj.build_ui()
  1871. elif isinstance(edited_obj, ExcellonObject):
  1872. self.exc_editor.deactivate()
  1873. edited_obj.build_ui()
  1874. else:
  1875. self.inform.emit('[WARNING_NOTCL] %s' %
  1876. _("Select a Gerber, Geometry or Excellon Object to update."))
  1877. return
  1878. elif response == bt_cancel:
  1879. return
  1880. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1881. # edited_obj.build_ui()
  1882. # Switch notebook to Selected page
  1883. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1884. else:
  1885. if isinstance(edited_obj, GeometryObject):
  1886. self.geo_editor.deactivate()
  1887. elif isinstance(edited_obj, GerberObject):
  1888. self.grb_editor.deactivate_grb_editor()
  1889. elif isinstance(edited_obj, ExcellonObject):
  1890. self.exc_editor.deactivate()
  1891. else:
  1892. self.inform.emit('[WARNING_NOTCL] %s' %
  1893. _("Select a Gerber, Geometry or Excellon Object to update."))
  1894. return
  1895. # if notebook is hidden we show it
  1896. if self.ui.splitter.sizes()[0] == 0:
  1897. self.ui.splitter.setSizes([1, 1])
  1898. # restore the call_source to app
  1899. self.call_source = 'app'
  1900. # edited_obj.plot()
  1901. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1902. self.ui.plot_tab_area.protectTab(0)
  1903. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1904. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1905. self.ui.project_frame.setDisabled(False)
  1906. def get_last_folder(self):
  1907. """
  1908. Get the folder path from where the last file was opened.
  1909. :return: String, last opened folder path
  1910. """
  1911. return self.defaults["global_last_folder"]
  1912. def get_last_save_folder(self):
  1913. """
  1914. Get the folder path from where the last file was saved.
  1915. :return: String, last saved folder path
  1916. """
  1917. loc = self.defaults["global_last_save_folder"]
  1918. if loc is None:
  1919. loc = self.defaults["global_last_folder"]
  1920. if loc is None:
  1921. loc = os.path.dirname(__file__)
  1922. return loc
  1923. def info(self, msg):
  1924. """
  1925. Informs the user. Normally on the status bar, optionally
  1926. also on the shell.
  1927. :param msg: Text to write.
  1928. :return: None
  1929. """
  1930. # Type of message in brackets at the beginning of the message.
  1931. match = re.search(r"\[(.*)\](.*)", msg)
  1932. if match:
  1933. level = match.group(1)
  1934. msg_ = match.group(2)
  1935. self.ui.fcinfo.set_status(str(msg_), level=level)
  1936. if level.lower() == "error":
  1937. self.shell_message(msg, error=True, show=True)
  1938. elif level.lower() == "warning":
  1939. self.shell_message(msg, warning=True, show=True)
  1940. elif level.lower() == "error_notcl":
  1941. self.shell_message(msg, error=True, show=False)
  1942. elif level.lower() == "warning_notcl":
  1943. self.shell_message(msg, warning=True, show=False)
  1944. elif level.lower() == "success":
  1945. self.shell_message(msg, success=True, show=False)
  1946. elif level.lower() == "selected":
  1947. self.shell_message(msg, selected=True, show=False)
  1948. else:
  1949. self.shell_message(msg, show=False)
  1950. else:
  1951. self.ui.fcinfo.set_status(str(msg), level="info")
  1952. # make sure that if the message is to clear the infobar with a space
  1953. # is not printed over and over on the shell
  1954. if msg != '':
  1955. self.shell_message(msg)
  1956. def on_import_preferences(self):
  1957. """
  1958. Loads the application default settings from a saved file into
  1959. ``self.defaults`` dictionary.
  1960. :return: None
  1961. """
  1962. self.defaults.report_usage("on_import_preferences")
  1963. App.log.debug("App.on_import_preferences()")
  1964. # Show file chooser
  1965. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  1966. try:
  1967. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1968. directory=self.data_path,
  1969. filter=filter_)
  1970. except TypeError:
  1971. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1972. filter=filter_)
  1973. filename = str(filename)
  1974. if filename == "":
  1975. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  1976. return
  1977. # Load in the defaults from the chosen file
  1978. self.defaults.load(filename=filename)
  1979. self.preferencesUiManager.on_preferences_edited()
  1980. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  1981. def on_export_preferences(self):
  1982. """
  1983. Save the defaults dictionary to a file.
  1984. :return: None
  1985. """
  1986. self.defaults.report_usage("on_export_preferences")
  1987. App.log.debug("on_export_preferences()")
  1988. # defaults_file_content = None
  1989. # Show file chooser
  1990. date = str(datetime.today()).rpartition('.')[0]
  1991. date = ''.join(c for c in date if c not in ':-')
  1992. date = date.replace(' ', '_')
  1993. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  1994. try:
  1995. filename, _f = FCFileSaveDialog.get_saved_filename(
  1996. caption=_("Export FlatCAM Preferences"),
  1997. directory=self.data_path + '/preferences_' + date,
  1998. filter=filter__
  1999. )
  2000. except TypeError:
  2001. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2002. filename = str(filename)
  2003. if filename == "":
  2004. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2005. return
  2006. # Update options
  2007. self.preferencesUiManager.defaults_read_form()
  2008. self.defaults.propagate_defaults()
  2009. # Save update options
  2010. try:
  2011. self.defaults.write(filename=filename)
  2012. except Exception:
  2013. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2014. return
  2015. if self.defaults["global_open_style"] is False:
  2016. self.file_opened.emit("preferences", filename)
  2017. self.file_saved.emit("preferences", filename)
  2018. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2019. def save_to_file(self, content_to_save, txt_content):
  2020. """
  2021. Save something to a file.
  2022. :return: None
  2023. """
  2024. self.defaults.report_usage("save_to_file")
  2025. App.log.debug("save_to_file()")
  2026. self.date = str(datetime.today()).rpartition('.')[0]
  2027. self.date = ''.join(c for c in self.date if c not in ':-')
  2028. self.date = self.date.replace(' ', '_')
  2029. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2030. path_to_save = self.defaults["global_last_save_folder"] if \
  2031. self.defaults["global_last_save_folder"] is not None else self.data_path
  2032. try:
  2033. filename, _f = FCFileSaveDialog.get_saved_filename(
  2034. caption=_("Save to file"),
  2035. directory=path_to_save + '/file_' + self.date,
  2036. filter=filter__
  2037. )
  2038. except TypeError:
  2039. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2040. filename = str(filename)
  2041. if filename == "":
  2042. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2043. return
  2044. else:
  2045. try:
  2046. with open(filename, 'w') as f:
  2047. ___ = f.read()
  2048. except PermissionError:
  2049. self.inform.emit('[WARNING] %s' %
  2050. _("Permission denied, saving not possible.\n"
  2051. "Most likely another app is holding the file open and not accessible."))
  2052. return
  2053. except IOError:
  2054. App.log.debug('Creating a new file ...')
  2055. f = open(filename, 'w')
  2056. f.close()
  2057. except Exception:
  2058. e = sys.exc_info()[0]
  2059. App.log.error("Could not load the file.")
  2060. App.log.error(str(e))
  2061. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2062. return
  2063. # Save content
  2064. if filename.rpartition('.')[2].lower() == 'html':
  2065. file_content = content_to_save
  2066. else:
  2067. file_content = txt_content
  2068. try:
  2069. with open(filename, "w") as f:
  2070. f.write(file_content)
  2071. except Exception:
  2072. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2073. return
  2074. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2075. def register_recent(self, kind, filename):
  2076. """
  2077. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2078. dictionary.
  2079. :param kind: type of file that was opened
  2080. :param filename: the path and file name for the file that was opened
  2081. :return:
  2082. """
  2083. self.log.debug("register_recent()")
  2084. self.log.debug(" %s" % kind)
  2085. self.log.debug(" %s" % filename)
  2086. record = {'kind': str(kind), 'filename': str(filename)}
  2087. if record in self.recent:
  2088. return
  2089. if record in self.recent_projects:
  2090. return
  2091. if record['kind'] == 'project':
  2092. self.recent_projects.insert(0, record)
  2093. else:
  2094. self.recent.insert(0, record)
  2095. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2096. self.recent.pop()
  2097. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2098. self.recent_projects.pop()
  2099. try:
  2100. f = open(self.data_path + '/recent.json', 'w')
  2101. except IOError:
  2102. App.log.error("Failed to open recent items file for writing.")
  2103. self.inform.emit('[ERROR_NOTCL] %s' %
  2104. _('Failed to open recent files file for writing.'))
  2105. return
  2106. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2107. f.close()
  2108. try:
  2109. fp = open(self.data_path + '/recent_projects.json', 'w')
  2110. except IOError:
  2111. App.log.error("Failed to open recent items file for writing.")
  2112. self.inform.emit('[ERROR_NOTCL] %s' %
  2113. _('Failed to open recent projects file for writing.'))
  2114. return
  2115. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2116. fp.close()
  2117. # Re-build the recent items menu
  2118. self.setup_recent_items()
  2119. def on_about(self):
  2120. """
  2121. Displays the "about" dialog found in the Menu --> Help.
  2122. :return: None
  2123. """
  2124. self.defaults.report_usage("on_about")
  2125. version = self.version
  2126. version_date = self.version_date
  2127. beta = self.beta
  2128. class AboutDialog(QtWidgets.QDialog):
  2129. def __init__(self, app, parent=None):
  2130. QtWidgets.QDialog.__init__(self, parent)
  2131. self.app = app
  2132. # Icon and title
  2133. self.setWindowIcon(parent.app_icon)
  2134. self.setWindowTitle(_("About FlatCAM"))
  2135. self.resize(600, 200)
  2136. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2137. # self.setStyleSheet(
  2138. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2139. # "background-attachment: fixed"
  2140. # )
  2141. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2142. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2143. # palette = QtGui.QPalette()
  2144. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2145. # self.setPalette(palette)
  2146. logo = QtWidgets.QLabel()
  2147. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2148. title = QtWidgets.QLabel(
  2149. "<font size=8><B>FlatCAM</B></font><BR>"
  2150. "{title}<BR>"
  2151. "<BR>"
  2152. "<BR>"
  2153. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2154. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2155. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2156. "<B>{issue}</B></a><BR>".format(
  2157. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2158. devel=_("Development"),
  2159. down=_("DOWNLOAD"),
  2160. issue=_("Issue tracker"))
  2161. )
  2162. title.setOpenExternalLinks(True)
  2163. closebtn = QtWidgets.QPushButton(_("Close"))
  2164. tab_widget = QtWidgets.QTabWidget()
  2165. description_label = QtWidgets.QLabel(
  2166. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2167. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2168. version=version,
  2169. beta=('BETA' if beta else ''),
  2170. date=version_date,
  2171. arch=platform.architecture()[0])
  2172. )
  2173. description_label.setOpenExternalLinks(True)
  2174. lic_lbl_header = QtWidgets.QLabel(
  2175. '%s:<br>%s<br>' % (
  2176. _('Licensed under the MIT license'),
  2177. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2178. "http://www.opensource.org/licenses/mit-license.php</a>"
  2179. )
  2180. )
  2181. lic_lbl_header.setOpenExternalLinks(True)
  2182. lic_lbl_body = QtWidgets.QLabel(
  2183. _(
  2184. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2185. 'of this software and associated documentation files (the "Software"), to deal\n'
  2186. 'in the Software without restriction, including without limitation the rights\n'
  2187. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2188. 'copies of the Software, and to permit persons to whom the Software is\n'
  2189. 'furnished to do so, subject to the following conditions:\n\n'
  2190. 'The above copyright notice and this permission notice shall be included in\n'
  2191. 'all copies or substantial portions of the Software.\n\n'
  2192. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2193. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2194. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2195. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2196. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2197. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2198. 'THE SOFTWARE.'
  2199. )
  2200. )
  2201. attributions_label = QtWidgets.QLabel(
  2202. _(
  2203. 'Some of the icons used are from the following sources:<br>'
  2204. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2205. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2206. 'title="Flaticon">www.flaticon.com</a></div>'
  2207. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2208. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2209. )
  2210. )
  2211. attributions_label.setOpenExternalLinks(True)
  2212. # layouts
  2213. layout1 = QtWidgets.QVBoxLayout()
  2214. layout1_1 = QtWidgets.QHBoxLayout()
  2215. layout1_2 = QtWidgets.QHBoxLayout()
  2216. layout2 = QtWidgets.QHBoxLayout()
  2217. layout3 = QtWidgets.QHBoxLayout()
  2218. self.setLayout(layout1)
  2219. layout1.addLayout(layout1_1)
  2220. layout1.addLayout(layout1_2)
  2221. layout1.addLayout(layout2)
  2222. layout1.addLayout(layout3)
  2223. layout1_1.addStretch()
  2224. layout1_1.addWidget(description_label)
  2225. layout1_2.addWidget(tab_widget)
  2226. self.splash_tab = QtWidgets.QWidget()
  2227. self.splash_tab.setObjectName("splash_about")
  2228. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2229. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2230. tab_widget.addTab(self.splash_tab, _("Splash"))
  2231. self.programmmers_tab = QtWidgets.QWidget()
  2232. self.programmmers_tab.setObjectName("programmers_about")
  2233. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2234. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2235. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2236. self.translators_tab = QtWidgets.QWidget()
  2237. self.translators_tab.setObjectName("translators_about")
  2238. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2239. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2240. tab_widget.addTab(self.translators_tab, _("Translators"))
  2241. self.license_tab = QtWidgets.QWidget()
  2242. self.license_tab.setObjectName("license_about")
  2243. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2244. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2245. tab_widget.addTab(self.license_tab, _("License"))
  2246. self.attributions_tab = QtWidgets.QWidget()
  2247. self.attributions_tab.setObjectName("attributions_about")
  2248. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2249. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2250. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2251. self.splash_tab_layout.addWidget(logo, stretch=0)
  2252. self.splash_tab_layout.addWidget(title, stretch=1)
  2253. pal = QtGui.QPalette()
  2254. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2255. self.prog_grid_lay = QtWidgets.QGridLayout()
  2256. self.prog_grid_lay.setHorizontalSpacing(20)
  2257. self.prog_grid_lay.setColumnStretch(0, 0)
  2258. self.prog_grid_lay.setColumnStretch(2, 1)
  2259. prog_widget = QtWidgets.QWidget()
  2260. prog_widget.setLayout(self.prog_grid_lay)
  2261. prog_scroll = QtWidgets.QScrollArea()
  2262. prog_scroll.setWidget(prog_widget)
  2263. prog_scroll.setWidgetResizable(True)
  2264. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2265. prog_scroll.setPalette(pal)
  2266. self.programmmers_tab_layout.addWidget(prog_scroll)
  2267. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2268. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2269. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2270. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2271. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2272. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2273. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2274. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2275. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2276. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2277. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2278. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2279. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2280. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2281. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2282. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2283. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2284. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2285. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2286. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2287. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2288. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2289. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2290. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2291. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2292. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2293. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2294. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2295. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2296. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2297. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2298. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2299. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2300. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2301. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2302. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2303. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2304. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2305. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2306. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2314. self.translator_grid_lay = QtWidgets.QGridLayout()
  2315. self.translator_grid_lay.setColumnStretch(0, 0)
  2316. self.translator_grid_lay.setColumnStretch(1, 0)
  2317. self.translator_grid_lay.setColumnStretch(2, 1)
  2318. self.translator_grid_lay.setColumnStretch(3, 0)
  2319. # trans_widget = QtWidgets.QWidget()
  2320. # trans_widget.setLayout(self.translator_grid_lay)
  2321. # self.translators_tab_layout.addWidget(trans_widget)
  2322. # self.translators_tab_layout.addStretch()
  2323. trans_widget = QtWidgets.QWidget()
  2324. trans_widget.setLayout(self.translator_grid_lay)
  2325. trans_scroll = QtWidgets.QScrollArea()
  2326. trans_scroll.setWidget(trans_widget)
  2327. trans_scroll.setWidgetResizable(True)
  2328. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2329. trans_scroll.setPalette(pal)
  2330. self.translators_tab_layout.addWidget(trans_scroll)
  2331. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2332. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2333. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2334. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2335. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2336. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2337. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2338. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2339. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2340. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2341. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2342. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2343. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2344. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2345. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2346. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2347. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Golfetto Massimiliano"), 4, 1)
  2348. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2349. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2350. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2351. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2352. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2353. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2354. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2355. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2356. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2357. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2358. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2359. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2360. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2361. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2362. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2363. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2364. self.translator_grid_lay.setColumnStretch(0, 0)
  2365. self.translators_tab_layout.addStretch()
  2366. self.license_tab_layout.addWidget(lic_lbl_header)
  2367. self.license_tab_layout.addWidget(lic_lbl_body)
  2368. self.license_tab_layout.addStretch()
  2369. self.attributions_tab_layout.addWidget(attributions_label)
  2370. self.attributions_tab_layout.addStretch()
  2371. layout3.addStretch()
  2372. layout3.addWidget(closebtn)
  2373. closebtn.clicked.connect(self.accept)
  2374. AboutDialog(app=self, parent=self.ui).exec_()
  2375. def on_readme(self):
  2376. class AboutDialog(QtWidgets.QDialog):
  2377. def __init__(self, app, parent=None):
  2378. QtWidgets.QDialog.__init__(self, parent)
  2379. self.app = app
  2380. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2381. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2382. "<b>new features</b></a>"
  2383. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>report bugs</b></a>"
  2384. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2385. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>donation</b></a>"
  2386. # Icon and title
  2387. self.setWindowIcon(parent.app_icon)
  2388. self.setWindowTitle(_("Important Information's"))
  2389. self.resize(720, 330)
  2390. logo = QtWidgets.QLabel()
  2391. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2392. content = QtWidgets.QLabel(
  2393. "This program is %s and free in a very wide meaning of the word.<br>"
  2394. "Yet it cannot evolve without <b>contributions</b>.<br><br>"
  2395. "If you want to see this application evolve and grow, or if you make money with it,<br>"
  2396. "you can <b>contribute</b> to the development yourself by:<br>"
  2397. "<ul>"
  2398. "<li>adding %s through a Pull Request on the Bitbucket repository</li>"
  2399. "<li>%s by providing the steps required to reproduce the bug</li>"
  2400. "<li>or by making a %s.</li>"
  2401. "</ul>"
  2402. "There are no strings attached.<br>"
  2403. "You don't have to make a %s, and it is totally optional but:"
  2404. "<ul>"
  2405. "<li>it will be welcomed with joy &#128077;</li>"
  2406. "<li>it will give me a reason to continue &#128513;</li>"
  2407. "</ul>" %
  2408. (open_source_link, new_features_link, bugs_link, donation_link, donation_link)
  2409. )
  2410. content.setOpenExternalLinks(True)
  2411. closebtn = QtWidgets.QPushButton(_("Close"))
  2412. # layouts
  2413. layout1 = QtWidgets.QVBoxLayout()
  2414. self.setLayout(layout1)
  2415. pal = QtGui.QPalette()
  2416. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2417. self.grid_lay = QtWidgets.QGridLayout()
  2418. self.grid_lay.setHorizontalSpacing(20)
  2419. self.grid_lay.setColumnStretch(0, 0)
  2420. self.grid_lay.setColumnStretch(1, 1)
  2421. content_widget = QtWidgets.QWidget()
  2422. content_widget.setLayout(self.grid_lay)
  2423. scroll_area = QtWidgets.QScrollArea()
  2424. scroll_area.setWidget(content_widget)
  2425. scroll_area.setWidgetResizable(True)
  2426. scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2427. scroll_area.setPalette(pal)
  2428. self.grid_lay.addWidget(logo, 0, 0)
  2429. self.grid_lay.addWidget(content, 0, 1)
  2430. layout1.addWidget(scroll_area)
  2431. layout2 = QtWidgets.QHBoxLayout()
  2432. layout1.addLayout(layout2)
  2433. layout2.addStretch()
  2434. layout2.addWidget(closebtn)
  2435. closebtn.clicked.connect(self.accept)
  2436. AboutDialog(app=self, parent=self.ui).exec_()
  2437. def install_bookmarks(self, book_dict=None):
  2438. """
  2439. Install the bookmarks actions in the Help menu -> Bookmarks
  2440. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2441. :return: None
  2442. """
  2443. if book_dict is None:
  2444. self.defaults["global_bookmarks"].update(
  2445. {
  2446. '1': ['FlatCAM', "http://flatcam.org"],
  2447. '2': ['Backup Site', ""]
  2448. }
  2449. )
  2450. else:
  2451. self.defaults["global_bookmarks"].clear()
  2452. self.defaults["global_bookmarks"].update(book_dict)
  2453. # first try to disconnect if somehow they get connected from elsewhere
  2454. for act in self.ui.menuhelp_bookmarks.actions():
  2455. try:
  2456. act.triggered.disconnect()
  2457. except TypeError:
  2458. pass
  2459. # clear all actions except the last one who is the Bookmark manager
  2460. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2461. pass
  2462. else:
  2463. self.ui.menuhelp_bookmarks.removeAction(act)
  2464. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2465. if self.defaults["global_bookmarks"]:
  2466. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2467. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2468. # the JSON is first making the keys as strings (therefore I have to use strings too
  2469. # or do the conversion :(
  2470. # )
  2471. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2472. # the '10' entry jsut after '1' therefore ordering as strings
  2473. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2474. key=lambda x: int(x[0]))
  2475. for entry, bookmark in sorted_bookmarks:
  2476. title = bookmark[0]
  2477. weblink = bookmark[1]
  2478. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2479. act.setText(title)
  2480. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2481. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2482. if title == 'Backup Site' and weblink == "":
  2483. act.triggered.connect(self.on_backup_site)
  2484. else:
  2485. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2486. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2487. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2488. def on_bookmarks_manager(self):
  2489. """
  2490. Adds the bookmark manager in a Tab in Plot Area
  2491. :return:
  2492. """
  2493. for idx in range(self.ui.plot_tab_area.count()):
  2494. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2495. # there can be only one instance of Bookmark Manager at one time
  2496. return
  2497. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2498. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2499. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2500. # add the tab if it was closed
  2501. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2502. # delete the absolute and relative position and messages in the infobar
  2503. self.ui.position_label.setText("")
  2504. # self.ui.rel_position_label.setText("")
  2505. # Switch plot_area to preferences page
  2506. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2507. def on_backup_site(self):
  2508. msgbox = QtWidgets.QMessageBox()
  2509. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2510. "1. FlatCAM.org website is down\n"
  2511. "2. Someone forked FlatCAM project and wants to point\n"
  2512. "to his own website\n\n"
  2513. "If you can't get any informations about FlatCAM beta\n"
  2514. "use the YouTube channel link from the Help menu."))
  2515. msgbox.setWindowTitle(_("Alternative website"))
  2516. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2517. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2518. msgbox.setDefaultButton(bt_yes)
  2519. msgbox.exec_()
  2520. # response = msgbox.clickedButton()
  2521. def on_file_savedefaults(self):
  2522. """
  2523. Callback for menu item File->Save Defaults. Saves application default options
  2524. ``self.defaults`` to current_defaults.FlatConfig.
  2525. :return: None
  2526. """
  2527. self.preferencesUiManager.save_defaults()
  2528. def final_save(self):
  2529. """
  2530. Callback for doing a preferences save to file whenever the application is about to quit.
  2531. If the project has changes, it will ask the user to save the project.
  2532. :return: None
  2533. """
  2534. if self.save_in_progress:
  2535. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2536. return
  2537. if self.should_we_save and self.collection.get_list():
  2538. msgbox = QtWidgets.QMessageBox()
  2539. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2540. "\n"
  2541. "Do you want to Save the project?"))
  2542. msgbox.setWindowTitle(_("Save changes"))
  2543. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2544. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2545. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2546. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2547. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2548. msgbox.setDefaultButton(bt_yes)
  2549. msgbox.exec_()
  2550. response = msgbox.clickedButton()
  2551. if response == bt_yes:
  2552. try:
  2553. self.trayIcon.hide()
  2554. except Exception:
  2555. pass
  2556. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2557. elif response == bt_no:
  2558. try:
  2559. self.trayIcon.hide()
  2560. except Exception:
  2561. pass
  2562. self.quit_application()
  2563. elif response == bt_cancel:
  2564. return
  2565. else:
  2566. try:
  2567. self.trayIcon.hide()
  2568. except Exception:
  2569. pass
  2570. self.quit_application()
  2571. def quit_application(self):
  2572. """
  2573. Called (as a pyslot or not) when the application is quit.
  2574. :return: None
  2575. """
  2576. self.preferencesUiManager.save_defaults(silent=True)
  2577. log.debug("App.quit_application() --> App Defaults saved.")
  2578. if self.cmd_line_headless != 1:
  2579. # save app state to file
  2580. stgs = QSettings("Open Source", "FlatCAM")
  2581. stgs.setValue('saved_gui_state', self.ui.saveState())
  2582. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2583. stgs.setValue(
  2584. 'language',
  2585. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2586. )
  2587. stgs.setValue(
  2588. 'notebook_font_size',
  2589. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2590. )
  2591. stgs.setValue(
  2592. 'axis_font_size',
  2593. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2594. )
  2595. stgs.setValue(
  2596. 'textbox_font_size',
  2597. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2598. )
  2599. stgs.setValue(
  2600. 'hud_font_size',
  2601. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2602. )
  2603. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2604. stgs.setValue(
  2605. 'machinist',
  2606. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2607. )
  2608. # This will write the setting to the platform specific storage.
  2609. del stgs
  2610. log.debug("App.quit_application() --> App UI state saved.")
  2611. # try to quit the Socket opened by ArgsThread class
  2612. try:
  2613. self.new_launch.stop.emit()
  2614. except Exception as err:
  2615. log.debug("App.quit_application() --> %s" % str(err))
  2616. # try to quit the QThread that run ArgsThread class
  2617. try:
  2618. self.th.quit()
  2619. except Exception as e:
  2620. log.debug("App.quit_application() --> %s" % str(e))
  2621. # terminate workers
  2622. self.workers.__del__()
  2623. # quit app by signalling for self.kill_app() method
  2624. # self.close_app_signal.emit()
  2625. QtWidgets.qApp.quit()
  2626. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2627. # we use the following command
  2628. minor_v = sys.version_info.minor
  2629. if minor_v < 8:
  2630. sys.exit(0)
  2631. else:
  2632. os._exit(0) # fix to work with Python 3.8
  2633. @staticmethod
  2634. def kill_app():
  2635. QtWidgets.qApp.quit()
  2636. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2637. # we use the following command
  2638. sys.exit(0)
  2639. def on_portable_checked(self, state):
  2640. """
  2641. Callback called when the checkbox in Preferences GUI is checked.
  2642. It will set the application as portable by creating the preferences and recent files in the
  2643. 'config' folder found in the FlatCAM installation folder.
  2644. :param state: boolean, the state of the checkbox when clicked/checked
  2645. :return:
  2646. """
  2647. line_no = 0
  2648. data = None
  2649. if sys.platform != 'win32':
  2650. # this won't work in Linux or MacOS
  2651. return
  2652. # test if the app was frozen and choose the path for the configuration file
  2653. if getattr(sys, "frozen", False) is True:
  2654. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2655. else:
  2656. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2657. config_file = current_data_path + '\\configuration.txt'
  2658. try:
  2659. with open(config_file, 'r') as f:
  2660. try:
  2661. data = f.readlines()
  2662. except Exception as e:
  2663. log.debug('App.__init__() -->%s' % str(e))
  2664. return
  2665. except FileNotFoundError:
  2666. pass
  2667. for line in data:
  2668. line = line.strip('\n')
  2669. param = str(line).rpartition('=')
  2670. if param[0] == 'portable':
  2671. break
  2672. line_no += 1
  2673. if state:
  2674. data[line_no] = 'portable=True\n'
  2675. # create the new defauults files
  2676. # create current_defaults.FlatConfig file if there is none
  2677. try:
  2678. f = open(current_data_path + '/current_defaults.FlatConfig')
  2679. f.close()
  2680. except IOError:
  2681. App.log.debug('Creating empty current_defaults.FlatConfig')
  2682. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2683. json.dump({}, f)
  2684. f.close()
  2685. # create factory_defaults.FlatConfig file if there is none
  2686. try:
  2687. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2688. f.close()
  2689. except IOError:
  2690. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2691. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2692. json.dump({}, f)
  2693. f.close()
  2694. try:
  2695. f = open(current_data_path + '/recent.json')
  2696. f.close()
  2697. except IOError:
  2698. App.log.debug('Creating empty recent.json')
  2699. f = open(current_data_path + '/recent.json', 'w')
  2700. json.dump([], f)
  2701. f.close()
  2702. try:
  2703. fp = open(current_data_path + '/recent_projects.json')
  2704. fp.close()
  2705. except IOError:
  2706. App.log.debug('Creating empty recent_projects.json')
  2707. fp = open(current_data_path + '/recent_projects.json', 'w')
  2708. json.dump([], fp)
  2709. fp.close()
  2710. # save the current defaults to the new defaults file
  2711. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2712. else:
  2713. data[line_no] = 'portable=False\n'
  2714. with open(config_file, 'w') as f:
  2715. f.writelines(data)
  2716. def on_register_files(self, obj_type=None):
  2717. """
  2718. Called whenever there is a need to register file extensions with FlatCAM.
  2719. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2720. :param obj_type: the type of object to be register for.
  2721. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2722. :return: None
  2723. """
  2724. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2725. new_reg_path = 'Software\\Classes\\'
  2726. # find if the current user is admin
  2727. try:
  2728. is_admin = os.getuid() == 0
  2729. except AttributeError:
  2730. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2731. if is_admin is True:
  2732. root_path = winreg.HKEY_LOCAL_MACHINE
  2733. else:
  2734. root_path = winreg.HKEY_CURRENT_USER
  2735. # create the keys
  2736. def set_reg(name, root_pth, new_reg_path, value):
  2737. try:
  2738. winreg.CreateKey(root_pth, new_reg_path)
  2739. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2740. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2741. return True
  2742. except WindowsError:
  2743. return False
  2744. # delete key in registry
  2745. def delete_reg(root_pth, reg_path, key_to_del):
  2746. key_to_del_path = reg_path + key_to_del
  2747. try:
  2748. winreg.DeleteKey(root_pth, key_to_del_path)
  2749. return True
  2750. except WindowsError:
  2751. return False
  2752. if obj_type is None or obj_type == 'excellon':
  2753. exc_list = \
  2754. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2755. exc_list = [x for x in exc_list if x != '']
  2756. # register all keys in the Preferences window
  2757. for ext in exc_list:
  2758. new_k = new_reg_path + '.%s' % ext
  2759. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2760. # and unregister those that are no longer in the Preferences windows but are in the file
  2761. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2762. if ext not in exc_list:
  2763. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2764. # now write the updated extensions to the self.defaults
  2765. # new_ext = ''
  2766. # for ext in exc_list:
  2767. # new_ext = new_ext + ext + ', '
  2768. # self.defaults["fa_excellon"] = new_ext
  2769. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2770. if obj_type is None or obj_type == 'gcode':
  2771. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2772. gco_list = [x for x in gco_list if x != '']
  2773. # register all keys in the Preferences window
  2774. for ext in gco_list:
  2775. new_k = new_reg_path + '.%s' % ext
  2776. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2777. # and unregister those that are no longer in the Preferences windows but are in the file
  2778. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2779. if ext not in gco_list:
  2780. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2781. # now write the updated extensions to the self.defaults
  2782. # new_ext = ''
  2783. # for ext in gco_list:
  2784. # new_ext = new_ext + ext + ', '
  2785. # self.defaults["fa_gcode"] = new_ext
  2786. self.inform.emit('[success] %s' %
  2787. _("Selected GCode file extensions registered with FlatCAM."))
  2788. if obj_type is None or obj_type == 'gerber':
  2789. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2790. grb_list = [x for x in grb_list if x != '']
  2791. # register all keys in the Preferences window
  2792. for ext in grb_list:
  2793. new_k = new_reg_path + '.%s' % ext
  2794. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2795. # and unregister those that are no longer in the Preferences windows but are in the file
  2796. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2797. if ext not in grb_list:
  2798. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2799. # now write the updated extensions to the self.defaults
  2800. # new_ext = ''
  2801. # for ext in grb_list:
  2802. # new_ext = new_ext + ext + ', '
  2803. # self.defaults["fa_gerber"] = new_ext
  2804. self.inform.emit('[success] %s' %
  2805. _("Selected Gerber file extensions registered with FlatCAM."))
  2806. def add_extension(self, ext_type):
  2807. """
  2808. Add a file extension to the list for a specific object
  2809. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2810. :return:
  2811. """
  2812. if ext_type == 'excellon':
  2813. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2814. if new_ext == '':
  2815. return
  2816. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2817. if new_ext in old_val:
  2818. return
  2819. old_val.append(new_ext)
  2820. old_val.sort()
  2821. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2822. if ext_type == 'gcode':
  2823. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2824. if new_ext == '':
  2825. return
  2826. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2827. if new_ext in old_val:
  2828. return
  2829. old_val.append(new_ext)
  2830. old_val.sort()
  2831. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2832. if ext_type == 'gerber':
  2833. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2834. if new_ext == '':
  2835. return
  2836. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2837. if new_ext in old_val:
  2838. return
  2839. old_val.append(new_ext)
  2840. old_val.sort()
  2841. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2842. if ext_type == 'keyword':
  2843. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2844. if new_kw == '':
  2845. return
  2846. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2847. if new_kw in old_val:
  2848. return
  2849. old_val.append(new_kw)
  2850. old_val.sort()
  2851. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2852. # update the self.myKeywords so the model is updated
  2853. self.autocomplete_kw_list = \
  2854. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2855. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2856. self.shell._edit.set_model_data(self.myKeywords)
  2857. def del_extension(self, ext_type):
  2858. """
  2859. Remove a file extension from the list for a specific object
  2860. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2861. :return:
  2862. """
  2863. if ext_type == 'excellon':
  2864. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2865. if new_ext == '':
  2866. return
  2867. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2868. if new_ext not in old_val:
  2869. return
  2870. old_val.remove(new_ext)
  2871. old_val.sort()
  2872. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2873. if ext_type == 'gcode':
  2874. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2875. if new_ext == '':
  2876. return
  2877. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2878. if new_ext not in old_val:
  2879. return
  2880. old_val.remove(new_ext)
  2881. old_val.sort()
  2882. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2883. if ext_type == 'gerber':
  2884. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2885. if new_ext == '':
  2886. return
  2887. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2888. if new_ext not in old_val:
  2889. return
  2890. old_val.remove(new_ext)
  2891. old_val.sort()
  2892. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  2893. if ext_type == 'keyword':
  2894. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  2895. if new_kw == '':
  2896. return
  2897. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2898. if new_kw not in old_val:
  2899. return
  2900. old_val.remove(new_kw)
  2901. old_val.sort()
  2902. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  2903. # update the self.myKeywords so the model is updated
  2904. self.autocomplete_kw_list = \
  2905. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  2906. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2907. self.shell._edit.set_model_data(self.myKeywords)
  2908. def restore_extensions(self, ext_type):
  2909. """
  2910. Restore all file extensions associations with FlatCAM, for a specific object
  2911. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2912. :return:
  2913. """
  2914. if ext_type == 'excellon':
  2915. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  2916. # for the ability to open Excellon files with .txt extension
  2917. new_exc_list = deepcopy(self.exc_list)
  2918. try:
  2919. new_exc_list.remove('txt')
  2920. except ValueError:
  2921. pass
  2922. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  2923. if ext_type == 'gcode':
  2924. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  2925. if ext_type == 'gerber':
  2926. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  2927. if ext_type == 'keyword':
  2928. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  2929. # update the self.myKeywords so the model is updated
  2930. self.autocomplete_kw_list = self.default_keywords
  2931. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2932. self.shell._edit.set_model_data(self.myKeywords)
  2933. def delete_all_extensions(self, ext_type):
  2934. """
  2935. Delete all file extensions associations with FlatCAM, for a specific object
  2936. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2937. :return:
  2938. """
  2939. if ext_type == 'excellon':
  2940. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  2941. if ext_type == 'gcode':
  2942. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  2943. if ext_type == 'gerber':
  2944. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  2945. if ext_type == 'keyword':
  2946. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  2947. # update the self.myKeywords so the model is updated
  2948. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  2949. self.shell._edit.set_model_data(self.myKeywords)
  2950. def on_edit_join(self, name=None):
  2951. """
  2952. Callback for Edit->Join. Joins the selected geometry objects into
  2953. a new one.
  2954. :return: None
  2955. """
  2956. self.defaults.report_usage("on_edit_join()")
  2957. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2958. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2959. geo_type_set = set()
  2960. objs = self.collection.get_selected()
  2961. if len(objs) < 2:
  2962. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  2963. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  2964. return 'fail'
  2965. for obj in objs:
  2966. geo_type_set.add(obj.multigeo)
  2967. # if len(geo_type_list) == 1 means that all list elements are the same
  2968. if len(geo_type_set) != 1:
  2969. self.inform.emit('[ERROR] %s' %
  2970. _("Failed join. The Geometry objects are of different types.\n"
  2971. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2972. "convert from one to another and retry joining \n"
  2973. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2974. "the result may not be what was expected. \n"
  2975. "Check the generated GCODE."))
  2976. return
  2977. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2978. if True in geo_type_set:
  2979. def initialize(geo_obj, app):
  2980. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True)
  2981. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2982. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2983. for v in geo_obj.tools.values():
  2984. v['data']['name'] = obj_name_multi
  2985. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  2986. else:
  2987. def initialize(geo_obj, app):
  2988. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False)
  2989. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  2990. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2991. for v in geo_obj.tools.values():
  2992. v['data']['name'] = obj_name_single
  2993. self.app_obj.new_object("geometry", obj_name_single, initialize)
  2994. self.should_we_save = True
  2995. def on_edit_join_exc(self):
  2996. """
  2997. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  2998. a new Excellon.
  2999. :return: None
  3000. """
  3001. self.defaults.report_usage("on_edit_join_exc()")
  3002. objs = self.collection.get_selected()
  3003. for obj in objs:
  3004. if not isinstance(obj, ExcellonObject):
  3005. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3006. return
  3007. if len(objs) < 2:
  3008. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3009. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3010. return 'fail'
  3011. def initialize(exc_obj, app):
  3012. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3013. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3014. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3015. self.should_we_save = True
  3016. def on_edit_join_grb(self):
  3017. """
  3018. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3019. a new Gerber object.
  3020. :return: None
  3021. """
  3022. self.defaults.report_usage("on_edit_join_grb()")
  3023. objs = self.collection.get_selected()
  3024. for obj in objs:
  3025. if not isinstance(obj, GerberObject):
  3026. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3027. return
  3028. if len(objs) < 2:
  3029. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3030. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3031. return 'fail'
  3032. def initialize(grb_obj, app):
  3033. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3034. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3035. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3036. self.should_we_save = True
  3037. def on_convert_singlegeo_to_multigeo(self):
  3038. """
  3039. Called for converting a Geometry object from single-geo to multi-geo.
  3040. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3041. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3042. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3043. the solid-geometry of that tool.
  3044. :return: None
  3045. """
  3046. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3047. obj = self.collection.get_active()
  3048. if obj is None:
  3049. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3050. return
  3051. if not isinstance(obj, GeometryObject):
  3052. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3053. return
  3054. obj.multigeo = True
  3055. for tooluid, dict_value in obj.tools.items():
  3056. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3057. if not isinstance(obj.solid_geometry, list):
  3058. obj.solid_geometry = [obj.solid_geometry]
  3059. # obj.solid_geometry[:] = []
  3060. obj.plot()
  3061. self.should_we_save = True
  3062. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3063. def on_convert_multigeo_to_singlegeo(self):
  3064. """
  3065. Called for converting a Geometry object from multi-geo to single-geo.
  3066. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3067. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3068. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3069. the solid-geometry of that tool.
  3070. :return: None
  3071. """
  3072. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3073. obj = self.collection.get_active()
  3074. if obj is None:
  3075. self.inform.emit('[ERROR_NOTCL] %s' %
  3076. _("Failed. Select a Geometry Object and try again."))
  3077. return
  3078. if not isinstance(obj, GeometryObject):
  3079. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3080. (_("Expected a GeometryObject, got"), type(obj)))
  3081. return
  3082. obj.multigeo = False
  3083. total_solid_geometry = []
  3084. for tooluid, dict_value in obj.tools.items():
  3085. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3086. # clear the original geometry
  3087. dict_value['solid_geometry'][:] = []
  3088. obj.solid_geometry = deepcopy(total_solid_geometry)
  3089. obj.plot()
  3090. self.should_we_save = True
  3091. self.inform.emit('[success] %s' %
  3092. _("A Geometry object was converted to SingleGeo type."))
  3093. def on_defaults_dict_change(self, field):
  3094. """
  3095. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3096. Edit -> Preferences tab window.
  3097. :param field: the key of the self.defaults dictionary that was changed.
  3098. :return: None
  3099. """
  3100. self.preferencesUiManager.defaults_write_form_field(field=field)
  3101. if field == "units":
  3102. self.set_screen_units(self.defaults['units'])
  3103. def set_screen_units(self, units):
  3104. """
  3105. Set the FlatCAM units on the status bar.
  3106. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3107. :return: None
  3108. """
  3109. self.ui.units_label.setText("[" + units.lower() + "]")
  3110. def on_toggle_units_click(self):
  3111. try:
  3112. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3113. except (TypeError, AttributeError):
  3114. pass
  3115. if self.defaults["units"] == 'MM':
  3116. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3117. else:
  3118. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3119. self.on_toggle_units(no_pref=True)
  3120. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3121. lambda: self.on_toggle_units(no_pref=False))
  3122. def on_toggle_units(self, no_pref=False):
  3123. """
  3124. Callback for the Units radio-button change in the Preferences tab.
  3125. Changes the application's default units adn for the project too.
  3126. If changing the project's units, the change propagates to all of
  3127. the objects in the project.
  3128. :return: None
  3129. """
  3130. self.defaults.report_usage("on_toggle_units")
  3131. if self.toggle_units_ignore:
  3132. return
  3133. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3134. # If option is the same, then ignore
  3135. if new_units == self.defaults["units"].upper():
  3136. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3137. return
  3138. # Keys in self.defaults for which to scale their values
  3139. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3140. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f", "gerber_vtipdia",
  3141. "gerber_vcutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3142. "gerber_editor_ma_high",
  3143. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3144. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3145. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3146. "excellon_feedrate_probe", "excellon_milling_dia",
  3147. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3148. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3149. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3150. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3151. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3152. "geometry_extracut_length", "geometry_z_pdepth",
  3153. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3154. 'cncjob_tooldia',
  3155. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3156. "tools_paintnewdia",
  3157. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3158. "tools_nccnewdia", "tools_ncc_offset_value",
  3159. "tools_2sided_drilldia",
  3160. "tools_film_boundary", "tools_film_scale_stroke",
  3161. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3162. "tools_cutout_depthperpass",
  3163. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3164. "tools_panelize_spacing_rows",
  3165. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3166. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3167. "tools_transform_buffer_dis",
  3168. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3169. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3170. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3171. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3172. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3173. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3174. "tools_cr_h2h_val", "tools_cr_dh_val",
  3175. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3176. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3177. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3178. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3179. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3180. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3181. "tools_copper_thieving_mask_clearance",
  3182. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3183. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3184. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3185. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3186. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3187. "tools_invert_margin",
  3188. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3189. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3190. def scale_defaults(sfactor):
  3191. for dim in dimensions:
  3192. if dim in [
  3193. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3194. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3195. 'tools_transform_mirror_point'
  3196. ]:
  3197. if self.defaults[dim] is None or self.defaults[dim] == '':
  3198. continue
  3199. try:
  3200. coordinates = self.defaults[dim].split(",")
  3201. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3202. coords_xy[0] *= sfactor
  3203. coords_xy[1] *= sfactor
  3204. self.defaults[dim] = "%.*f, %.*f" % (
  3205. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3206. except Exception as e:
  3207. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3208. elif dim in [
  3209. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3210. ]:
  3211. if self.defaults[dim] is None or self.defaults[dim] == '':
  3212. continue
  3213. try:
  3214. self.defaults[dim] = float(self.defaults[dim])
  3215. tools_diameters = [self.defaults[dim]]
  3216. except ValueError:
  3217. try:
  3218. tools_string = self.defaults[dim].split(",")
  3219. tools_diameters = [eval(a) for a in tools_string if a != '']
  3220. except Exception as e:
  3221. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3222. continue
  3223. self.defaults[dim] = ''
  3224. td_len = len(tools_diameters)
  3225. if td_len > 1:
  3226. for t in range(td_len):
  3227. tools_diameters[t] *= sfactor
  3228. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3229. else:
  3230. tools_diameters[0] *= sfactor
  3231. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3232. elif dim in ['global_gridx', 'global_gridy']:
  3233. # format the number of decimals to the one specified in self.decimals
  3234. try:
  3235. val = float(self.defaults[dim]) * sfactor
  3236. except Exception as e:
  3237. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3238. continue
  3239. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3240. else:
  3241. # the number of decimals for the rest is kept unchanged
  3242. if self.defaults[dim]:
  3243. try:
  3244. val = float(self.defaults[dim]) * sfactor
  3245. except Exception as e:
  3246. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3247. continue
  3248. self.defaults[dim] = val
  3249. # The scaling factor depending on choice of units.
  3250. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3251. # Changing project units. Warn user.
  3252. msgbox = QtWidgets.QMessageBox()
  3253. msgbox.setWindowTitle(_("Toggle Units"))
  3254. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3255. msgbox.setText(_("Changing the units of the project\n"
  3256. "will scale all objects.\n\n"
  3257. "Do you want to continue?"))
  3258. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3259. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3260. msgbox.setDefaultButton(bt_ok)
  3261. msgbox.exec_()
  3262. response = msgbox.clickedButton()
  3263. if response == bt_ok:
  3264. if no_pref is False:
  3265. self.preferencesUiManager.defaults_read_form()
  3266. scale_defaults(factor)
  3267. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3268. self.defaults["units"] = new_units
  3269. # update the defaults from form, some may assume that the conversion is enough and it's not
  3270. self.on_options_app2project()
  3271. # update the objects
  3272. for obj in self.collection.get_list():
  3273. obj.convert_units(new_units)
  3274. # make that the properties stored in the object are also updated
  3275. self.app_obj.object_changed.emit(obj)
  3276. # rebuild the object UI
  3277. obj.build_ui()
  3278. # change this only if the workspace is active
  3279. if self.defaults['global_workspace'] is True:
  3280. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3281. # adjust the grid values on the main toolbar
  3282. val_x = float(self.defaults['global_gridx']) * factor
  3283. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3284. current = self.collection.get_active()
  3285. if current is not None:
  3286. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3287. if not isinstance(current, GeometryObject):
  3288. current.to_form()
  3289. # replot all objects
  3290. self.plot_all()
  3291. # set the status labels to reflect the current FlatCAM units
  3292. self.set_screen_units(new_units)
  3293. # signal to the app that we changed the object properties and it should save the project
  3294. self.should_we_save = True
  3295. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3296. else:
  3297. # Undo toggling
  3298. self.toggle_units_ignore = True
  3299. if self.defaults['units'].upper() == 'MM':
  3300. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3301. else:
  3302. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3303. self.toggle_units_ignore = False
  3304. # store the grid values so they are not changed in the next step
  3305. val_x = float(self.defaults['global_gridx'])
  3306. val_y = float(self.defaults['global_gridy'])
  3307. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3308. self.preferencesUiManager.defaults_read_form()
  3309. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3310. # in self.defaults from the GUI elements but
  3311. # I don't want it for the grid values, so I update them here
  3312. self.defaults['global_gridx'] = val_x
  3313. self.defaults['global_gridy'] = val_y
  3314. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3315. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3316. def on_toggle_axis(self):
  3317. self.defaults.report_usage("on_toggle_axis()")
  3318. if self.toggle_axis is False:
  3319. if self.is_legacy is False:
  3320. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3321. parent=self.plotcanvas.view.scene)
  3322. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3323. parent=self.plotcanvas.view.scene)
  3324. else:
  3325. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3326. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3327. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3328. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3329. self.plotcanvas.canvas.draw()
  3330. self.inform.emit(_("Axis enabled."))
  3331. self.toggle_axis = True
  3332. else:
  3333. if self.is_legacy is False:
  3334. self.plotcanvas.v_line.parent = None
  3335. self.plotcanvas.h_line.parent = None
  3336. else:
  3337. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3338. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3339. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3340. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3341. self.plotcanvas.canvas.draw()
  3342. self.inform.emit(_("Axis disabled."))
  3343. self.toggle_axis = False
  3344. def on_toggle_hud(self):
  3345. new_state = False if self.plotcanvas.hud_enabled else True
  3346. self.plotcanvas.on_toggle_hud(state=new_state)
  3347. if new_state is False:
  3348. self.inform.emit(_("HUD disabled."))
  3349. else:
  3350. self.inform.emit(_("HUD enabled."))
  3351. def on_toggle_grid_lines(self):
  3352. self.defaults.report_usage("on_toggle_grd_lines()")
  3353. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3354. if tt_settings.contains("theme"):
  3355. theme = tt_settings.value('theme', type=str)
  3356. else:
  3357. theme = 'white'
  3358. if self.toggle_grid_lines is False:
  3359. if self.is_legacy is False:
  3360. if theme == 'white':
  3361. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3362. else:
  3363. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3364. else:
  3365. self.plotcanvas.axes.grid(True)
  3366. try:
  3367. self.plotcanvas.canvas.draw()
  3368. except IndexError:
  3369. pass
  3370. pass
  3371. self.inform.emit(_("Grid enabled."))
  3372. self.toggle_grid_lines = True
  3373. else:
  3374. if self.is_legacy is False:
  3375. if theme == 'white':
  3376. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3377. else:
  3378. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3379. else:
  3380. self.plotcanvas.axes.grid(False)
  3381. try:
  3382. self.plotcanvas.canvas.draw()
  3383. except IndexError:
  3384. pass
  3385. self.toggle_grid_lines = False
  3386. self.inform.emit(_("Grid disabled."))
  3387. if self.is_legacy is False:
  3388. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3389. # - perhaps is a bug in VisPy implementation
  3390. if self.grid_status():
  3391. self.app_cursor.enabled = False
  3392. self.app_cursor.enabled = True
  3393. else:
  3394. self.app_cursor.enabled = True
  3395. self.app_cursor.enabled = False
  3396. def on_tab_rmb_click(self, checked):
  3397. self.ui.notebook.set_detachable(val=checked)
  3398. self.defaults["global_tabs_detachable"] = checked
  3399. self.ui.plot_tab_area.set_detachable(val=checked)
  3400. self.defaults["global_tabs_detachable"] = checked
  3401. def on_tab_setup_context_menu(self):
  3402. initial_checked = self.defaults["global_tabs_detachable"]
  3403. action_name = str(_("Detachable Tabs"))
  3404. action = QtWidgets.QAction(self)
  3405. action.setCheckable(True)
  3406. action.setText(action_name)
  3407. action.setChecked(initial_checked)
  3408. self.ui.notebook.tabBar.addAction(action)
  3409. self.ui.plot_tab_area.tabBar.addAction(action)
  3410. try:
  3411. action.triggered.disconnect()
  3412. except TypeError:
  3413. pass
  3414. action.triggered.connect(self.on_tab_rmb_click)
  3415. def on_deselect_all(self):
  3416. self.collection.set_all_inactive()
  3417. self.delete_selection_shape()
  3418. def on_workspace_modified(self):
  3419. # self.save_defaults(silent=True)
  3420. self.plotcanvas.delete_workspace()
  3421. self.preferencesUiManager.defaults_read_form()
  3422. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3423. def on_workspace(self):
  3424. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3425. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3426. self.inform.emit(_("Workspace enabled."))
  3427. else:
  3428. self.plotcanvas.delete_workspace()
  3429. self.inform.emit(_("Workspace disabled."))
  3430. self.preferencesUiManager.defaults_read_form()
  3431. # self.save_defaults(silent=True)
  3432. def on_workspace_toggle(self):
  3433. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3434. try:
  3435. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3436. except TypeError:
  3437. pass
  3438. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3439. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3440. self.on_workspace()
  3441. def on_cursor_type(self, val):
  3442. """
  3443. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3444. :return: None
  3445. """
  3446. self.app_cursor.enabled = False
  3447. if val == 'small':
  3448. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3449. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3450. self.app_cursor = self.plotcanvas.new_cursor()
  3451. else:
  3452. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3453. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3454. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3455. if self.ui.grid_snap_btn.isChecked():
  3456. self.app_cursor.enabled = True
  3457. else:
  3458. self.app_cursor.enabled = False
  3459. def on_tool_add_keypress(self):
  3460. # ## Current application units in Upper Case
  3461. self.units = self.defaults['units'].upper()
  3462. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3463. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3464. if notebook_widget_name == 'selected_tab':
  3465. if self.collection.get_active().kind == 'geometry':
  3466. # Tool add works for Geometry only if Advanced is True in Preferences
  3467. if self.defaults["global_app_level"] == 'a':
  3468. tool_add_popup = FCInputDialog(title="New Tool ...",
  3469. text='Enter a Tool Diameter:',
  3470. min=0.0000, max=99.9999, decimals=4)
  3471. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3472. val, ok = tool_add_popup.get_value()
  3473. if ok:
  3474. if float(val) == 0:
  3475. self.inform.emit('[WARNING_NOTCL] %s' %
  3476. _("Please enter a tool diameter with non-zero value, in Float format."))
  3477. return
  3478. self.collection.get_active().on_tool_add(dia=float(val))
  3479. else:
  3480. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3481. else:
  3482. msgbox = QtWidgets.QMessageBox()
  3483. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3484. "Go to Preferences -> General - Show Advanced Options."))
  3485. msgbox.setWindowTitle("Tool adding ...")
  3486. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3487. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3488. msgbox.setDefaultButton(bt_ok)
  3489. msgbox.exec_()
  3490. # work only if the notebook tab on focus is the Tools_Tab
  3491. if notebook_widget_name == 'tool_tab':
  3492. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3493. # and only if the tool is NCC Tool
  3494. if tool_widget == self.ncclear_tool.toolName:
  3495. self.ncclear_tool.on_add_tool_by_key()
  3496. # and only if the tool is Paint Area Tool
  3497. elif tool_widget == self.paint_tool.toolName:
  3498. self.paint_tool.on_add_tool_by_key()
  3499. # and only if the tool is Solder Paste Dispensing Tool
  3500. elif tool_widget == self.paste_tool.toolName:
  3501. self.paste_tool.on_add_tool_by_key()
  3502. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3503. # See description below.
  3504. def on_delete_keypress(self):
  3505. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3506. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3507. if notebook_widget_name == 'selected_tab':
  3508. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3509. self.collection.get_active().on_tool_delete()
  3510. # work only if the notebook tab on focus is the Tools_Tab
  3511. elif notebook_widget_name == 'tool_tab':
  3512. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3513. # and only if the tool is NCC Tool
  3514. if tool_widget == self.ncclear_tool.toolName:
  3515. self.ncclear_tool.on_tool_delete()
  3516. # and only if the tool is Paint Tool
  3517. elif tool_widget == self.paint_tool.toolName:
  3518. self.paint_tool.on_tool_delete()
  3519. # and only if the tool is Solder Paste Dispensing Tool
  3520. elif tool_widget == self.paste_tool.toolName:
  3521. self.paste_tool.on_tool_delete()
  3522. else:
  3523. self.on_delete()
  3524. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3525. # some screens you have to be careful where you hover with your mouse.
  3526. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3527. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3528. # Complicated, I know :)
  3529. def on_delete(self, force_deletion=False):
  3530. """
  3531. Delete the currently selected FlatCAMObjs.
  3532. :param force_deletion: used by Tcl command
  3533. :return: None
  3534. """
  3535. self.defaults.report_usage("on_delete()")
  3536. response = None
  3537. bt_ok = None
  3538. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3539. # a geometry object before we update it.
  3540. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3541. and self.grb_editor.editor_active is False:
  3542. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3543. msgbox = QtWidgets.QMessageBox()
  3544. msgbox.setWindowTitle(_("Delete objects"))
  3545. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3546. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3547. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3548. "the selected objects?"))
  3549. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3550. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3551. msgbox.setDefaultButton(bt_ok)
  3552. msgbox.exec_()
  3553. response = msgbox.clickedButton()
  3554. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3555. response = bt_ok
  3556. if response == bt_ok:
  3557. if self.collection.get_active():
  3558. self.log.debug("App.on_delete()")
  3559. for obj_active in self.collection.get_selected():
  3560. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3561. if obj_active.kind == 'gerber':
  3562. for el in obj_active.mark_shapes:
  3563. obj_active.mark_shapes[el].clear(update=True)
  3564. obj_active.mark_shapes[el].enabled = False
  3565. # obj_active.mark_shapes[el] = None
  3566. del el
  3567. elif isinstance(obj_active, CNCJobObject):
  3568. try:
  3569. obj_active.text_col.enabled = False
  3570. del obj_active.text_col
  3571. obj_active.annotation.clear(update=True)
  3572. del obj_active.annotation
  3573. except AttributeError as e:
  3574. log.debug(
  3575. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3576. )
  3577. while self.collection.get_selected():
  3578. self.delete_first_selected()
  3579. self.inform.emit('%s...' % _("Object(s) deleted"))
  3580. # make sure that the selection shape is deleted, too
  3581. self.delete_selection_shape()
  3582. # if there are no longer objects delete also the exclusion areas shapes
  3583. if not self.collection.get_list():
  3584. self.exc_areas.clear_shapes()
  3585. else:
  3586. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3587. else:
  3588. self.inform.emit(_("Save the work in Editor and try again ..."))
  3589. def delete_first_selected(self):
  3590. # Keep this for later
  3591. try:
  3592. sel_obj = self.collection.get_active()
  3593. name = sel_obj.options["name"]
  3594. isPlotted = sel_obj.options["plot"]
  3595. except AttributeError:
  3596. self.log.debug("Nothing selected for deletion")
  3597. return
  3598. if self.is_legacy is True:
  3599. # Remove plot only if the object was plotted otherwise delaxes will fail
  3600. if isPlotted:
  3601. try:
  3602. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3603. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3604. except Exception as e:
  3605. log.debug("App.delete_first_selected() --> %s" % str(e))
  3606. self.plotcanvas.auto_adjust_axes()
  3607. # Remove from dictionary
  3608. self.collection.delete_active()
  3609. # Clear form
  3610. self.setup_component_editor()
  3611. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3612. def on_set_origin(self):
  3613. """
  3614. Set the origin to the left mouse click position
  3615. :return: None
  3616. """
  3617. # display the message for the user
  3618. # and ask him to click on the desired position
  3619. self.defaults.report_usage("on_set_origin()")
  3620. def origin_replot():
  3621. def worker_task():
  3622. with self.proc_container.new('%s...' % _("Plotting")):
  3623. for obj in self.collection.get_list():
  3624. obj.plot()
  3625. self.plotcanvas.fit_view()
  3626. if self.is_legacy:
  3627. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3628. else:
  3629. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3630. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3631. self.inform.emit(_('Click to set the origin ...'))
  3632. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3633. # first disconnect it as it may have been used by something else
  3634. try:
  3635. self.replot_signal.disconnect()
  3636. except TypeError:
  3637. pass
  3638. self.replot_signal[list].connect(origin_replot)
  3639. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3640. """
  3641. :param event:
  3642. :param location:
  3643. :param noplot:
  3644. :param use_thread:
  3645. :return:
  3646. """
  3647. noplot_sig = noplot
  3648. def worker_task():
  3649. with self.proc_container.new(_("Setting Origin...")):
  3650. obj_list = self.collection.get_list()
  3651. for obj in obj_list:
  3652. obj.offset((x, y))
  3653. self.app_obj.object_changed.emit(obj)
  3654. # Update the object bounding box options
  3655. a, b, c, d = obj.bounds()
  3656. obj.options['xmin'] = a
  3657. obj.options['ymin'] = b
  3658. obj.options['xmax'] = c
  3659. obj.options['ymax'] = d
  3660. self.inform.emit('[success] %s...' % _('Origin set'))
  3661. for obj in obj_list:
  3662. out_name = obj.options["name"]
  3663. if obj.kind == 'gerber':
  3664. obj.source_file = self.export_gerber(
  3665. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3666. elif obj.kind == 'excellon':
  3667. obj.source_file = self.export_excellon(
  3668. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3669. if noplot_sig is False:
  3670. self.replot_signal.emit([])
  3671. if location is not None:
  3672. if len(location) != 2:
  3673. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3674. return 'fail'
  3675. x, y = location
  3676. if use_thread is True:
  3677. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3678. else:
  3679. worker_task()
  3680. self.should_we_save = True
  3681. return
  3682. if event is not None and event.button == 1:
  3683. if self.is_legacy is False:
  3684. event_pos = event.pos
  3685. else:
  3686. event_pos = (event.xdata, event.ydata)
  3687. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3688. if self.grid_status():
  3689. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3690. else:
  3691. pos = pos_canvas
  3692. x = 0 - pos[0]
  3693. y = 0 - pos[1]
  3694. if use_thread is True:
  3695. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3696. else:
  3697. worker_task()
  3698. self.should_we_save = True
  3699. def on_move2origin(self, use_thread=True):
  3700. """
  3701. Move selected objects to origin.
  3702. :param use_thread: Control if to use threaded operation. Boolean.
  3703. :return:
  3704. """
  3705. def worker_task():
  3706. with self.proc_container.new(_("Moving to Origin...")):
  3707. obj_list = self.collection.get_selected()
  3708. if not obj_list:
  3709. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3710. return
  3711. xminlist = []
  3712. yminlist = []
  3713. # first get a bounding box to fit all
  3714. for obj in obj_list:
  3715. xmin, ymin, xmax, ymax = obj.bounds()
  3716. xminlist.append(xmin)
  3717. yminlist.append(ymin)
  3718. # get the minimum x,y for all objects selected
  3719. x = min(xminlist)
  3720. y = min(yminlist)
  3721. for obj in obj_list:
  3722. obj.offset((-x, -y))
  3723. self.app_obj.object_changed.emit(obj)
  3724. # Update the object bounding box options
  3725. a, b, c, d = obj.bounds()
  3726. obj.options['xmin'] = a
  3727. obj.options['ymin'] = b
  3728. obj.options['xmax'] = c
  3729. obj.options['ymax'] = d
  3730. for obj in obj_list:
  3731. obj.plot()
  3732. for obj in obj_list:
  3733. out_name = obj.options["name"]
  3734. if obj.kind == 'gerber':
  3735. obj.source_file = self.export_gerber(
  3736. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3737. elif obj.kind == 'excellon':
  3738. obj.source_file = self.export_excellon(
  3739. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3740. self.inform.emit('[success] %s...' % _('Origin set'))
  3741. if use_thread is True:
  3742. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3743. else:
  3744. worker_task()
  3745. self.should_we_save = True
  3746. def on_jump_to(self, custom_location=None, fit_center=True):
  3747. """
  3748. Jump to a location by setting the mouse cursor location.
  3749. :param custom_location: Jump to a specified point. (x, y) tuple.
  3750. :param fit_center: If to fit view. Boolean.
  3751. :return:
  3752. """
  3753. self.defaults.report_usage("on_jump_to()")
  3754. if not custom_location:
  3755. dia_box_location = None
  3756. try:
  3757. dia_box_location = eval(self.clipboard.text())
  3758. except Exception:
  3759. pass
  3760. if type(dia_box_location) == tuple:
  3761. dia_box_location = str(dia_box_location)
  3762. else:
  3763. dia_box_location = None
  3764. # dia_box = Dialog_box(title=_("Jump to ..."),
  3765. # label=_("Enter the coordinates in format X,Y:"),
  3766. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3767. # initial_text=dia_box_location)
  3768. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3769. label=_("Enter the coordinates in format X,Y:"),
  3770. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3771. initial_text=dia_box_location,
  3772. reference=self.defaults['global_jump_ref'])
  3773. if dia_box.ok is True:
  3774. try:
  3775. location = eval(dia_box.location)
  3776. if not isinstance(location, tuple):
  3777. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3778. return
  3779. if dia_box.reference == 'rel':
  3780. rel_x = self.mouse[0] + location[0]
  3781. rel_y = self.mouse[1] + location[1]
  3782. location = (rel_x, rel_y)
  3783. self.defaults['global_jump_ref'] = dia_box.reference
  3784. except Exception:
  3785. return
  3786. else:
  3787. return
  3788. else:
  3789. location = custom_location
  3790. self.jump_signal.emit(location)
  3791. if fit_center:
  3792. self.plotcanvas.fit_center(loc=location)
  3793. cursor = QtGui.QCursor()
  3794. if self.is_legacy is False:
  3795. # I don't know where those differences come from but they are constant for the current
  3796. # execution of the application and they are multiples of a value around 0.0263mm.
  3797. # In a random way sometimes they are more sometimes they are less
  3798. # if units == 'MM':
  3799. # cal_factor = 0.0263
  3800. # else:
  3801. # cal_factor = 0.0263 / 25.4
  3802. cal_location = (location[0], location[1])
  3803. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3804. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3805. j_pos = (
  3806. int(canvas_origin.x() + round(jump_loc[0])),
  3807. int(canvas_origin.y() + round(jump_loc[1]))
  3808. )
  3809. cursor.setPos(j_pos[0], j_pos[1])
  3810. else:
  3811. # find the canvas origin which is in the top left corner
  3812. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3813. # determine the coordinates for the lowest left point of the canvas
  3814. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3815. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3816. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3817. # canvas) and the point (width, height) is in the top-right location
  3818. loc = self.plotcanvas.axes.transData.transform_point(location)
  3819. j_pos = (
  3820. int(x0 + loc[0]),
  3821. int(y0 - loc[1])
  3822. )
  3823. cursor.setPos(j_pos[0], j_pos[1])
  3824. self.plotcanvas.mouse = [location[0], location[1]]
  3825. if self.defaults["global_cursor_color_enabled"] is True:
  3826. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3827. else:
  3828. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3829. if self.grid_status():
  3830. # Update cursor
  3831. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3832. symbol='++', edge_color=self.cursor_color_3D,
  3833. edge_width=self.defaults["global_cursor_width"],
  3834. size=self.defaults["global_cursor_size"])
  3835. # Set the relative position label
  3836. dx = location[0] - float(self.rel_point1[0])
  3837. dy = location[1] - float(self.rel_point1[1])
  3838. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3839. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3840. # # Set the position label
  3841. #
  3842. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3843. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3844. units = self.defaults["units"].lower()
  3845. self.plotcanvas.text_hud.text = \
  3846. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3847. dx, units, dy, units, location[0], units, location[1], units)
  3848. self.inform.emit('[success] %s' % _("Done."))
  3849. return location
  3850. def on_locate(self, obj, fit_center=True):
  3851. """
  3852. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3853. :param obj: The object on which to locate certain points
  3854. :param fit_center: If to fit view. Boolean.
  3855. :return: A point location. (x, y) tuple.
  3856. """
  3857. self.defaults.report_usage("on_locate()")
  3858. if obj is None:
  3859. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3860. return 'fail'
  3861. class DialogBoxChoice(QtWidgets.QDialog):
  3862. def __init__(self, title=None, icon=None, choice='bl'):
  3863. """
  3864. :param title: string with the window title
  3865. """
  3866. super(DialogBoxChoice, self).__init__()
  3867. self.ok = False
  3868. self.setWindowIcon(icon)
  3869. self.setWindowTitle(str(title))
  3870. self.form = QtWidgets.QFormLayout(self)
  3871. self.ref_radio = RadioSet([
  3872. {"label": _("Bottom-Left"), "value": "bl"},
  3873. {"label": _("Top-Left"), "value": "tl"},
  3874. {"label": _("Bottom-Right"), "value": "br"},
  3875. {"label": _("Top-Right"), "value": "tr"},
  3876. {"label": _("Center"), "value": "c"}
  3877. ], orientation='vertical', stretch=False)
  3878. self.ref_radio.set_value(choice)
  3879. self.form.addRow(self.ref_radio)
  3880. self.button_box = QtWidgets.QDialogButtonBox(
  3881. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3882. Qt.Horizontal, parent=self)
  3883. self.form.addRow(self.button_box)
  3884. self.button_box.accepted.connect(self.accept)
  3885. self.button_box.rejected.connect(self.reject)
  3886. if self.exec_() == QtWidgets.QDialog.Accepted:
  3887. self.ok = True
  3888. self.location_point = self.ref_radio.get_value()
  3889. else:
  3890. self.ok = False
  3891. self.location_point = None
  3892. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3893. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3894. choice=self.defaults['global_locate_pt'])
  3895. if dia_box.ok is True:
  3896. try:
  3897. location_point = dia_box.location_point
  3898. self.defaults['global_locate_pt'] = dia_box.location_point
  3899. except Exception:
  3900. return
  3901. else:
  3902. return
  3903. loc_b = obj.bounds()
  3904. if location_point == 'bl':
  3905. location = (loc_b[0], loc_b[1])
  3906. elif location_point == 'tl':
  3907. location = (loc_b[0], loc_b[3])
  3908. elif location_point == 'br':
  3909. location = (loc_b[2], loc_b[1])
  3910. elif location_point == 'tr':
  3911. location = (loc_b[2], loc_b[3])
  3912. else:
  3913. # center
  3914. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3915. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3916. location = (cx, cy)
  3917. self.locate_signal.emit(location, location_point)
  3918. if fit_center:
  3919. self.plotcanvas.fit_center(loc=location)
  3920. cursor = QtGui.QCursor()
  3921. if self.is_legacy is False:
  3922. # I don't know where those differences come from but they are constant for the current
  3923. # execution of the application and they are multiples of a value around 0.0263mm.
  3924. # In a random way sometimes they are more sometimes they are less
  3925. # if units == 'MM':
  3926. # cal_factor = 0.0263
  3927. # else:
  3928. # cal_factor = 0.0263 / 25.4
  3929. cal_location = (location[0], location[1])
  3930. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3931. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3932. j_pos = (
  3933. int(canvas_origin.x() + round(jump_loc[0])),
  3934. int(canvas_origin.y() + round(jump_loc[1]))
  3935. )
  3936. cursor.setPos(j_pos[0], j_pos[1])
  3937. else:
  3938. # find the canvas origin which is in the top left corner
  3939. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3940. # determine the coordinates for the lowest left point of the canvas
  3941. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3942. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3943. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3944. # canvas) and the point (width, height) is in the top-right location
  3945. loc = self.plotcanvas.axes.transData.transform_point(location)
  3946. j_pos = (
  3947. int(x0 + loc[0]),
  3948. int(y0 - loc[1])
  3949. )
  3950. cursor.setPos(j_pos[0], j_pos[1])
  3951. self.plotcanvas.mouse = [location[0], location[1]]
  3952. if self.defaults["global_cursor_color_enabled"] is True:
  3953. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3954. else:
  3955. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3956. if self.grid_status():
  3957. # Update cursor
  3958. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3959. symbol='++', edge_color=self.cursor_color_3D,
  3960. edge_width=self.defaults["global_cursor_width"],
  3961. size=self.defaults["global_cursor_size"])
  3962. # Set the relative position label
  3963. self.dx = location[0] - float(self.rel_point1[0])
  3964. self.dy = location[1] - float(self.rel_point1[1])
  3965. # Set the position label
  3966. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3967. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3968. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3969. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  3970. units = self.defaults["units"].lower()
  3971. self.plotcanvas.text_hud.text = \
  3972. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3973. self.dx, units, self.dy, units, location[0], units, location[1], units)
  3974. self.inform.emit('[success] %s' % _("Done."))
  3975. return location
  3976. def on_copy_command(self):
  3977. """
  3978. Will copy a selection of objects, creating new objects.
  3979. :return:
  3980. """
  3981. self.defaults.report_usage("on_copy_command()")
  3982. def initialize(obj_init, app):
  3983. """
  3984. :param obj_init: the new object
  3985. :type obj_init: class
  3986. :param app: An instance of the App class
  3987. :type app: App
  3988. :return: None
  3989. :rtype:
  3990. """
  3991. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  3992. try:
  3993. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  3994. except AttributeError:
  3995. pass
  3996. try:
  3997. obj_init.apertures = deepcopy(obj.apertures)
  3998. except AttributeError:
  3999. pass
  4000. try:
  4001. if obj.tools:
  4002. obj_init.tools = deepcopy(obj.tools)
  4003. except Exception as err:
  4004. log.debug("App.on_copy_command() --> %s" % str(err))
  4005. try:
  4006. obj_init.source_file = deepcopy(obj.source_file)
  4007. except (AttributeError, TypeError):
  4008. pass
  4009. def initialize_excellon(obj_init, app):
  4010. obj_init.source_file = deepcopy(obj.source_file)
  4011. obj_init.tools = deepcopy(obj.tools)
  4012. # drills are offset, so they need to be deep copied
  4013. obj_init.drills = deepcopy(obj.drills)
  4014. # slots are offset, so they need to be deep copied
  4015. obj_init.slots = deepcopy(obj.slots)
  4016. obj_init.create_geometry()
  4017. def initialize_script(obj_init, app_obj):
  4018. obj_init.source_file = deepcopy(obj.source_file)
  4019. def initialize_document(obj_init, app_obj):
  4020. obj_init.source_file = deepcopy(obj.source_file)
  4021. for obj in self.collection.get_selected():
  4022. obj_name = obj.options["name"]
  4023. try:
  4024. if isinstance(obj, ExcellonObject):
  4025. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4026. elif isinstance(obj, GerberObject):
  4027. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4028. elif isinstance(obj, GeometryObject):
  4029. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4030. elif isinstance(obj, ScriptObject):
  4031. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4032. elif isinstance(obj, DocumentObject):
  4033. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4034. except Exception as e:
  4035. return "Operation failed: %s" % str(e)
  4036. def on_copy_object2(self, custom_name):
  4037. def initialize_geometry(obj_init, app):
  4038. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4039. try:
  4040. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4041. except AttributeError:
  4042. pass
  4043. try:
  4044. obj_init.apertures = deepcopy(obj.apertures)
  4045. except AttributeError:
  4046. pass
  4047. try:
  4048. if obj.tools:
  4049. obj_init.tools = deepcopy(obj.tools)
  4050. except Exception as ee:
  4051. log.debug("on_copy_object2() --> %s" % str(ee))
  4052. def initialize_gerber(obj_init, app):
  4053. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4054. obj_init.apertures = deepcopy(obj.apertures)
  4055. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4056. def initialize_excellon(obj_init, app):
  4057. obj_init.tools = deepcopy(obj.tools)
  4058. # drills are offset, so they need to be deep copied
  4059. obj_init.drills = deepcopy(obj.drills)
  4060. # slots are offset, so they need to be deep copied
  4061. obj_init.slots = deepcopy(obj.slots)
  4062. obj_init.create_geometry()
  4063. for obj in self.collection.get_selected():
  4064. obj_name = obj.options["name"]
  4065. try:
  4066. if isinstance(obj, ExcellonObject):
  4067. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4068. elif isinstance(obj, GerberObject):
  4069. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4070. elif isinstance(obj, GeometryObject):
  4071. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4072. except Exception as er:
  4073. return "Operation failed: %s" % str(er)
  4074. def on_rename_object(self, text):
  4075. """
  4076. Will rename an object.
  4077. :param text: New name for the object.
  4078. :return:
  4079. """
  4080. self.defaults.report_usage("on_rename_object()")
  4081. named_obj = self.collection.get_active()
  4082. for obj in named_obj:
  4083. if obj is list:
  4084. self.on_rename_object(text)
  4085. else:
  4086. try:
  4087. obj.options['name'] = text
  4088. except Exception as e:
  4089. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4090. def convert_any2geo(self):
  4091. """
  4092. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4093. :return:
  4094. """
  4095. self.defaults.report_usage("convert_any2geo()")
  4096. def initialize(obj_init, app):
  4097. obj_init.solid_geometry = obj.solid_geometry
  4098. try:
  4099. obj_init.follow_geometry = obj.follow_geometry
  4100. except AttributeError:
  4101. pass
  4102. try:
  4103. obj_init.apertures = obj.apertures
  4104. except AttributeError:
  4105. pass
  4106. try:
  4107. if obj.tools:
  4108. obj_init.tools = obj.tools
  4109. except AttributeError:
  4110. pass
  4111. def initialize_excellon(obj_init, app):
  4112. # objs = self.collection.get_selected()
  4113. # GeometryObject.merge(objs, obj)
  4114. solid_geo = []
  4115. for tool in obj.tools:
  4116. for geo in obj.tools[tool]['solid_geometry']:
  4117. solid_geo.append(geo)
  4118. obj_init.solid_geometry = deepcopy(solid_geo)
  4119. if not self.collection.get_selected():
  4120. log.warning("App.convert_any2geo --> No object selected")
  4121. self.inform.emit('[WARNING_NOTCL] %s' %
  4122. _("No object is selected. Select an object and try again."))
  4123. return
  4124. for obj in self.collection.get_selected():
  4125. obj_name = obj.options["name"]
  4126. try:
  4127. if isinstance(obj, ExcellonObject):
  4128. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4129. else:
  4130. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4131. except Exception as e:
  4132. return "Operation failed: %s" % str(e)
  4133. def convert_any2gerber(self):
  4134. """
  4135. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4136. :return:
  4137. """
  4138. self.defaults.report_usage("convert_any2gerber()")
  4139. def initialize_geometry(obj_init, app):
  4140. apertures = {}
  4141. apid = 0
  4142. apertures[str(apid)] = {}
  4143. apertures[str(apid)]['geometry'] = []
  4144. for obj_orig in obj.solid_geometry:
  4145. new_elem = {}
  4146. new_elem['solid'] = obj_orig
  4147. try:
  4148. new_elem['follow'] = obj_orig.exterior
  4149. except AttributeError:
  4150. pass
  4151. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4152. apertures[str(apid)]['size'] = 0.0
  4153. apertures[str(apid)]['type'] = 'C'
  4154. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4155. obj_init.apertures = deepcopy(apertures)
  4156. def initialize_excellon(obj_init, app):
  4157. apertures = {}
  4158. apid = 10
  4159. for tool in obj.tools:
  4160. apertures[str(apid)] = {}
  4161. apertures[str(apid)]['geometry'] = []
  4162. for geo in obj.tools[tool]['solid_geometry']:
  4163. new_el = {}
  4164. new_el['solid'] = geo
  4165. new_el['follow'] = geo.exterior
  4166. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4167. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4168. apertures[str(apid)]['type'] = 'C'
  4169. apid += 1
  4170. # create solid_geometry
  4171. solid_geometry = []
  4172. for apid in apertures:
  4173. for geo_el in apertures[apid]['geometry']:
  4174. solid_geometry.append(geo_el['solid'])
  4175. solid_geometry = MultiPolygon(solid_geometry)
  4176. solid_geometry = solid_geometry.buffer(0.0000001)
  4177. obj_init.solid_geometry = deepcopy(solid_geometry)
  4178. obj_init.apertures = deepcopy(apertures)
  4179. # clear the working objects (perhaps not necessary due of Python GC)
  4180. apertures.clear()
  4181. if not self.collection.get_selected():
  4182. log.warning("App.convert_any2gerber --> No object selected")
  4183. self.inform.emit('[WARNING_NOTCL] %s' %
  4184. _("No object is selected. Select an object and try again."))
  4185. return
  4186. for obj in self.collection.get_selected():
  4187. obj_name = obj.options["name"]
  4188. try:
  4189. if isinstance(obj, ExcellonObject):
  4190. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4191. elif isinstance(obj, GeometryObject):
  4192. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4193. else:
  4194. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4195. except Exception as e:
  4196. return "Operation failed: %s" % str(e)
  4197. def abort_all_tasks(self):
  4198. """
  4199. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4200. on the first possible occasion.
  4201. :return:
  4202. """
  4203. if self.abort_flag is False:
  4204. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4205. self.abort_flag = True
  4206. self.cleanup.emit()
  4207. def app_is_idle(self):
  4208. if self.abort_flag:
  4209. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4210. self.abort_flag = False
  4211. def on_selectall(self):
  4212. """
  4213. Will draw a selection box shape around the selected objects.
  4214. :return:
  4215. """
  4216. self.defaults.report_usage("on_selectall()")
  4217. # delete the possible selection box around a possible selected object
  4218. self.delete_selection_shape()
  4219. for name in self.collection.get_names():
  4220. self.collection.set_active(name)
  4221. curr_sel_obj = self.collection.get_by_name(name)
  4222. # create the selection box around the selected object
  4223. if self.defaults['global_selection_shape'] is True:
  4224. self.draw_selection_shape(curr_sel_obj)
  4225. def on_preferences(self):
  4226. """
  4227. Adds the Preferences in a Tab in Plot Area
  4228. :return:
  4229. """
  4230. # add the tab if it was closed
  4231. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4232. # delete the absolute and relative position and messages in the infobar
  4233. self.ui.position_label.setText("")
  4234. # self.ui.rel_position_label.setText("")
  4235. # Switch plot_area to preferences page
  4236. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4237. # self.ui.show()
  4238. # detect changes in the preferences
  4239. for idx in range(self.ui.pref_tab_area.count()):
  4240. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4241. try:
  4242. try:
  4243. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4244. except (TypeError, AttributeError):
  4245. pass
  4246. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4247. except AttributeError:
  4248. pass
  4249. try:
  4250. try:
  4251. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4252. except (TypeError, AttributeError):
  4253. pass
  4254. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4255. except AttributeError:
  4256. pass
  4257. try:
  4258. try:
  4259. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4260. except (TypeError, AttributeError):
  4261. pass
  4262. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4263. except AttributeError:
  4264. pass
  4265. try:
  4266. try:
  4267. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4268. except (TypeError, AttributeError):
  4269. pass
  4270. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4271. except AttributeError:
  4272. pass
  4273. try:
  4274. try:
  4275. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4276. except (TypeError, AttributeError):
  4277. pass
  4278. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4279. except AttributeError:
  4280. pass
  4281. def on_tools_database(self, source='app'):
  4282. """
  4283. Adds the Tools Database in a Tab in Plot Area.
  4284. :return:
  4285. """
  4286. for idx in range(self.ui.plot_tab_area.count()):
  4287. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4288. # there can be only one instance of Tools Database at one time
  4289. return
  4290. if source == 'app':
  4291. self.tools_db_tab = ToolsDB2(
  4292. app=self,
  4293. parent=self.ui,
  4294. callback_on_edited=self.on_tools_db_edited,
  4295. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4296. )
  4297. elif source == 'ncc':
  4298. self.tools_db_tab = ToolsDB2(
  4299. app=self,
  4300. parent=self.ui,
  4301. callback_on_edited=self.on_tools_db_edited,
  4302. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4303. )
  4304. elif source == 'paint':
  4305. self.tools_db_tab = ToolsDB2(
  4306. app=self,
  4307. parent=self.ui,
  4308. callback_on_edited=self.on_tools_db_edited,
  4309. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4310. )
  4311. # add the tab if it was closed
  4312. try:
  4313. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4314. self.tools_db_tab.setObjectName("database_tab")
  4315. except Exception as e:
  4316. log.debug("App.on_tools_database() --> %s" % str(e))
  4317. return
  4318. # delete the absolute and relative position and messages in the infobar
  4319. self.ui.position_label.setText("")
  4320. # self.ui.rel_position_label.setText("")
  4321. # Switch plot_area to preferences page
  4322. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4323. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4324. self.tools_db_tab.ui_connect()
  4325. def on_tools_db_edited(self):
  4326. """
  4327. Executed whenever a tool is edited in Tools Database.
  4328. Will color the text of the Tools Database tab to Red color.
  4329. :return:
  4330. """
  4331. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4332. for idx in range(self.ui.plot_tab_area.count()):
  4333. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4334. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4335. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4336. self.tools_db_changed_flag = True
  4337. def on_geometry_tool_add_from_db_executed(self, tool):
  4338. """
  4339. Here add the tool from DB in the selected geometry object.
  4340. :return:
  4341. """
  4342. tool_from_db = deepcopy(tool)
  4343. obj = self.collection.get_active()
  4344. if isinstance(obj, GeometryObject):
  4345. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4346. # close the tab and delete it
  4347. for idx in range(self.ui.plot_tab_area.count()):
  4348. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4349. wdg = self.ui.plot_tab_area.widget(idx)
  4350. wdg.deleteLater()
  4351. self.ui.plot_tab_area.removeTab(idx)
  4352. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4353. else:
  4354. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4355. def on_plot_area_tab_closed(self, tab_obj_name):
  4356. """
  4357. Executed whenever a QTab is closed in the Plot Area.
  4358. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4359. :return:
  4360. """
  4361. if tab_obj_name == "preferences_tab":
  4362. self.preferencesUiManager.on_close_preferences_tab()
  4363. elif tab_obj_name == "database_tab":
  4364. # disconnect the signals from the table widget in tab
  4365. self.tools_db_tab.ui_disconnect()
  4366. if self.tools_db_changed_flag is True:
  4367. msgbox = QtWidgets.QMessageBox()
  4368. msgbox.setText(_("One or more Tools are edited.\n"
  4369. "Do you want to update the Tools Database?"))
  4370. msgbox.setWindowTitle(_("Save Tools Database"))
  4371. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4372. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4373. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4374. msgbox.setDefaultButton(bt_yes)
  4375. msgbox.exec_()
  4376. response = msgbox.clickedButton()
  4377. if response == bt_yes:
  4378. self.tools_db_tab.on_save_tools_db()
  4379. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4380. else:
  4381. self.tools_db_changed_flag = False
  4382. self.inform.emit('')
  4383. return
  4384. self.tools_db_tab.deleteLater()
  4385. elif tab_obj_name == "text_editor_tab":
  4386. self.toggle_codeeditor = False
  4387. elif tab_obj_name == "bookmarks_tab":
  4388. self.book_dialog_tab.rebuild_actions()
  4389. self.book_dialog_tab.deleteLater()
  4390. else:
  4391. return
  4392. # def on_plotarea_tab_closed(self, tab_idx):
  4393. # """
  4394. #
  4395. # :param tab_idx: Index of the Tab from the plotarea that was closed
  4396. # :return:
  4397. # """
  4398. # widget = self.ui.plot_tab_area.widget(tab_idx)
  4399. #
  4400. # if widget is not None:
  4401. # widget.deleteLater()
  4402. # self.ui.plot_tab_area.removeTab(tab_idx)
  4403. def on_flipy(self):
  4404. """
  4405. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4406. :return:
  4407. """
  4408. self.defaults.report_usage("on_flipy()")
  4409. obj_list = self.collection.get_selected()
  4410. xminlist = []
  4411. yminlist = []
  4412. xmaxlist = []
  4413. ymaxlist = []
  4414. if not obj_list:
  4415. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4416. else:
  4417. try:
  4418. # first get a bounding box to fit all
  4419. for obj in obj_list:
  4420. xmin, ymin, xmax, ymax = obj.bounds()
  4421. xminlist.append(xmin)
  4422. yminlist.append(ymin)
  4423. xmaxlist.append(xmax)
  4424. ymaxlist.append(ymax)
  4425. # get the minimum x,y and maximum x,y for all objects selected
  4426. xminimal = min(xminlist)
  4427. yminimal = min(yminlist)
  4428. xmaximal = max(xmaxlist)
  4429. ymaximal = max(ymaxlist)
  4430. px = 0.5 * (xminimal + xmaximal)
  4431. py = 0.5 * (yminimal + ymaximal)
  4432. # execute mirroring
  4433. for obj in obj_list:
  4434. obj.mirror('X', [px, py])
  4435. obj.plot()
  4436. self.app_obj.object_changed.emit(obj)
  4437. self.inform.emit('[success] %s' %
  4438. _("Flip on Y axis done."))
  4439. except Exception as e:
  4440. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4441. return
  4442. def on_flipx(self):
  4443. """
  4444. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4445. :return:
  4446. """
  4447. self.defaults.report_usage("on_flipx()")
  4448. obj_list = self.collection.get_selected()
  4449. xminlist = []
  4450. yminlist = []
  4451. xmaxlist = []
  4452. ymaxlist = []
  4453. if not obj_list:
  4454. self.inform.emit('[WARNING_NOTCL] %s' %
  4455. _("No object selected to Flip on X axis."))
  4456. else:
  4457. try:
  4458. # first get a bounding box to fit all
  4459. for obj in obj_list:
  4460. xmin, ymin, xmax, ymax = obj.bounds()
  4461. xminlist.append(xmin)
  4462. yminlist.append(ymin)
  4463. xmaxlist.append(xmax)
  4464. ymaxlist.append(ymax)
  4465. # get the minimum x,y and maximum x,y for all objects selected
  4466. xminimal = min(xminlist)
  4467. yminimal = min(yminlist)
  4468. xmaximal = max(xmaxlist)
  4469. ymaximal = max(ymaxlist)
  4470. px = 0.5 * (xminimal + xmaximal)
  4471. py = 0.5 * (yminimal + ymaximal)
  4472. # execute mirroring
  4473. for obj in obj_list:
  4474. obj.mirror('Y', [px, py])
  4475. obj.plot()
  4476. self.app_obj.object_changed.emit(obj)
  4477. self.inform.emit('[success] %s' %
  4478. _("Flip on X axis done."))
  4479. except Exception as e:
  4480. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4481. return
  4482. def on_rotate(self, silent=False, preset=None):
  4483. """
  4484. Executed when Options -> Rotate Selection menu entry is clicked.
  4485. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4486. :param preset: A value to be used as predefined angle for rotation.
  4487. :return:
  4488. """
  4489. self.defaults.report_usage("on_rotate()")
  4490. obj_list = self.collection.get_selected()
  4491. xminlist = []
  4492. yminlist = []
  4493. xmaxlist = []
  4494. ymaxlist = []
  4495. if not obj_list:
  4496. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4497. else:
  4498. if silent is False:
  4499. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4500. min=-360, max=360, decimals=4,
  4501. init_val=float(self.defaults['tools_transform_rotate']))
  4502. num, ok = rotatebox.get_value()
  4503. else:
  4504. num = preset
  4505. ok = True
  4506. if ok:
  4507. try:
  4508. # first get a bounding box to fit all
  4509. for obj in obj_list:
  4510. xmin, ymin, xmax, ymax = obj.bounds()
  4511. xminlist.append(xmin)
  4512. yminlist.append(ymin)
  4513. xmaxlist.append(xmax)
  4514. ymaxlist.append(ymax)
  4515. # get the minimum x,y and maximum x,y for all objects selected
  4516. xminimal = min(xminlist)
  4517. yminimal = min(yminlist)
  4518. xmaximal = max(xmaxlist)
  4519. ymaximal = max(ymaxlist)
  4520. px = 0.5 * (xminimal + xmaximal)
  4521. py = 0.5 * (yminimal + ymaximal)
  4522. for sel_obj in obj_list:
  4523. sel_obj.rotate(-float(num), point=(px, py))
  4524. sel_obj.plot()
  4525. self.app_obj.object_changed.emit(sel_obj)
  4526. self.inform.emit('[success] %s' % _("Rotation done."))
  4527. except Exception as e:
  4528. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4529. return
  4530. def on_skewx(self):
  4531. """
  4532. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4533. :return:
  4534. """
  4535. self.defaults.report_usage("on_skewx()")
  4536. obj_list = self.collection.get_selected()
  4537. xminlist = []
  4538. yminlist = []
  4539. if not obj_list:
  4540. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4541. else:
  4542. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4543. min=-360, max=360, decimals=4,
  4544. init_val=float(self.defaults['tools_transform_skew_x']))
  4545. num, ok = skewxbox.get_value()
  4546. if ok:
  4547. # first get a bounding box to fit all
  4548. for obj in obj_list:
  4549. xmin, ymin, xmax, ymax = obj.bounds()
  4550. xminlist.append(xmin)
  4551. yminlist.append(ymin)
  4552. # get the minimum x,y and maximum x,y for all objects selected
  4553. xminimal = min(xminlist)
  4554. yminimal = min(yminlist)
  4555. for obj in obj_list:
  4556. obj.skew(num, 0, point=(xminimal, yminimal))
  4557. obj.plot()
  4558. self.app_obj.object_changed.emit(obj)
  4559. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4560. def on_skewy(self):
  4561. """
  4562. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4563. :return:
  4564. """
  4565. self.defaults.report_usage("on_skewy()")
  4566. obj_list = self.collection.get_selected()
  4567. xminlist = []
  4568. yminlist = []
  4569. if not obj_list:
  4570. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4571. else:
  4572. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4573. min=-360, max=360, decimals=4,
  4574. init_val=float(self.defaults['tools_transform_skew_y']))
  4575. num, ok = skewybox.get_value()
  4576. if ok:
  4577. # first get a bounding box to fit all
  4578. for obj in obj_list:
  4579. xmin, ymin, xmax, ymax = obj.bounds()
  4580. xminlist.append(xmin)
  4581. yminlist.append(ymin)
  4582. # get the minimum x,y and maximum x,y for all objects selected
  4583. xminimal = min(xminlist)
  4584. yminimal = min(yminlist)
  4585. for obj in obj_list:
  4586. obj.skew(0, num, point=(xminimal, yminimal))
  4587. obj.plot()
  4588. self.app_obj.object_changed.emit(obj)
  4589. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4590. def on_plots_updated(self):
  4591. """
  4592. Callback used to report when the plots have changed.
  4593. Adjust axes and zooms to fit.
  4594. :return: None
  4595. """
  4596. if self.is_legacy is False:
  4597. self.plotcanvas.update()
  4598. else:
  4599. self.plotcanvas.auto_adjust_axes()
  4600. self.on_zoom_fit()
  4601. self.collection.update_view()
  4602. # self.inform.emit(_("Plots updated ..."))
  4603. def on_toolbar_replot(self):
  4604. """
  4605. Callback for toolbar button. Re-plots all objects.
  4606. :return: None
  4607. """
  4608. self.defaults.report_usage("on_toolbar_replot")
  4609. self.log.debug("on_toolbar_replot()")
  4610. try:
  4611. self.collection.get_active().read_form()
  4612. except AttributeError:
  4613. self.log.debug("on_toolbar_replot(): AttributeError")
  4614. pass
  4615. self.plot_all()
  4616. def grid_status(self):
  4617. return True if self.ui.grid_snap_btn.isChecked() else False
  4618. def populate_cmenu_grids(self):
  4619. units = self.defaults['units'].lower()
  4620. # for act in self.ui.cmenu_gridmenu.actions():
  4621. # act.triggered.disconnect()
  4622. self.ui.cmenu_gridmenu.clear()
  4623. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4624. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4625. _("Grid On/Off"))
  4626. grid_toggle.setCheckable(True)
  4627. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4628. self.ui.cmenu_gridmenu.addSeparator()
  4629. for grid in sorted_list:
  4630. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4631. "%s" % str(grid))
  4632. action.triggered.connect(self.set_grid)
  4633. self.ui.cmenu_gridmenu.addSeparator()
  4634. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4635. _("Add"))
  4636. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4637. _("Delete"))
  4638. grid_add.triggered.connect(self.on_grid_add)
  4639. grid_delete.triggered.connect(self.on_grid_delete)
  4640. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4641. def set_grid(self):
  4642. menu_action = self.sender()
  4643. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4644. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4645. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4646. def on_grid_add(self):
  4647. # ## Current application units in lower Case
  4648. units = self.defaults['units'].lower()
  4649. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4650. text=_('Enter a Grid Value:'),
  4651. min=0.0000, max=99.9999, decimals=4)
  4652. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4653. val, ok = grid_add_popup.get_value()
  4654. if ok:
  4655. if float(val) == 0:
  4656. self.inform.emit('[WARNING_NOTCL] %s' %
  4657. _("Please enter a grid value with non-zero value, in Float format."))
  4658. return
  4659. else:
  4660. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4661. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4662. self.inform.emit('[success] %s...' % _("New Grid added"))
  4663. else:
  4664. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4665. else:
  4666. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4667. def on_grid_delete(self):
  4668. # ## Current application units in lower Case
  4669. units = self.defaults['units'].lower()
  4670. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4671. text='Enter a Grid Value:',
  4672. min=0.0000, max=99.9999, decimals=4)
  4673. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4674. val, ok = grid_del_popup.get_value()
  4675. if ok:
  4676. if float(val) == 0:
  4677. self.inform.emit('[WARNING_NOTCL] %s' %
  4678. _("Please enter a grid value with non-zero value, in Float format."))
  4679. return
  4680. else:
  4681. try:
  4682. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4683. except ValueError:
  4684. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4685. return
  4686. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4687. else:
  4688. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4689. def on_shortcut_list(self):
  4690. self.defaults.report_usage("on_shortcut_list()")
  4691. # add the tab if it was closed
  4692. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4693. # delete the absolute and relative position and messages in the infobar
  4694. self.ui.position_label.setText("")
  4695. # self.ui.rel_position_label.setText("")
  4696. # Switch plot_area to preferences page
  4697. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4698. # self.ui.show()
  4699. def on_select_tab(self, name):
  4700. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4701. if self.ui.splitter.sizes()[0] == 0:
  4702. self.ui.splitter.setSizes([1, 1])
  4703. else:
  4704. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4705. self.ui.splitter.setSizes([0, 1])
  4706. if name == 'project':
  4707. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4708. elif name == 'selected':
  4709. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4710. elif name == 'tool':
  4711. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4712. def on_copy_name(self):
  4713. self.defaults.report_usage("on_copy_name()")
  4714. obj = self.collection.get_active()
  4715. try:
  4716. name = obj.options["name"]
  4717. except AttributeError:
  4718. log.debug("on_copy_name() --> No object selected to copy it's name")
  4719. self.inform.emit('[WARNING_NOTCL]%s' %
  4720. _(" No object selected to copy it's name"))
  4721. return
  4722. self.clipboard.setText(name)
  4723. self.inform.emit(_("Name copied on clipboard ..."))
  4724. def on_mouse_click_over_plot(self, event):
  4725. """
  4726. Default actions are:
  4727. :param event: Contains information about the event, like which button
  4728. was clicked, the pixel coordinates and the axes coordinates.
  4729. :return: None
  4730. """
  4731. self.pos = []
  4732. if self.is_legacy is False:
  4733. event_pos = event.pos
  4734. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4735. # # Set the mouse button for panning
  4736. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4737. else:
  4738. event_pos = (event.xdata, event.ydata)
  4739. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4740. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4741. # So it can receive key presses
  4742. self.plotcanvas.native.setFocus()
  4743. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4744. if self.grid_status():
  4745. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4746. else:
  4747. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4748. try:
  4749. if event.button == 1:
  4750. # Reset here the relative coordinates so there is a new reference on the click position
  4751. if self.rel_point1 is None:
  4752. self.rel_point1 = self.pos
  4753. else:
  4754. self.rel_point2 = copy(self.rel_point1)
  4755. self.rel_point1 = self.pos
  4756. self.on_mouse_move_over_plot(event, origin_click=True)
  4757. except Exception as e:
  4758. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4759. def on_mouse_double_click_over_plot(self, event):
  4760. if event.button == 1:
  4761. self.doubleclick = True
  4762. def on_mouse_move_over_plot(self, event, origin_click=None):
  4763. """
  4764. Callback for the mouse motion event over the plot.
  4765. :param event: Contains information about the event.
  4766. :param origin_click
  4767. :return: None
  4768. """
  4769. if self.is_legacy is False:
  4770. event_pos = event.pos
  4771. if self.defaults["global_pan_button"] == '2':
  4772. pan_button = 2
  4773. else:
  4774. pan_button = 3
  4775. self.event_is_dragging = event.is_dragging
  4776. else:
  4777. event_pos = (event.xdata, event.ydata)
  4778. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4779. if self.defaults["global_pan_button"] == '2':
  4780. pan_button = 3
  4781. else:
  4782. pan_button = 2
  4783. self.event_is_dragging = self.plotcanvas.is_dragging
  4784. # So it can receive key presses but not when the Tcl Shell is active
  4785. if not self.ui.shell_dock.isVisible():
  4786. if not self.plotcanvas.native.hasFocus():
  4787. self.plotcanvas.native.setFocus()
  4788. self.pos_jump = event_pos
  4789. self.ui.popMenu.mouse_is_panning = False
  4790. if origin_click is None:
  4791. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4792. if event.button == pan_button and self.event_is_dragging == 1:
  4793. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4794. if self.ui.popMenu.popup_active:
  4795. self.ui.popMenu.popup_active = False
  4796. return
  4797. self.ui.popMenu.mouse_is_panning = True
  4798. return
  4799. if self.rel_point1 is not None:
  4800. try: # May fail in case mouse not within axes
  4801. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4802. if pos_canvas[0] is None or pos_canvas[1] is None:
  4803. return
  4804. if self.grid_status():
  4805. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4806. # Update cursor
  4807. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4808. symbol='++', edge_color=self.cursor_color_3D,
  4809. edge_width=self.defaults["global_cursor_width"],
  4810. size=self.defaults["global_cursor_size"])
  4811. else:
  4812. pos = (pos_canvas[0], pos_canvas[1])
  4813. self.dx = pos[0] - float(self.rel_point1[0])
  4814. self.dy = pos[1] - float(self.rel_point1[1])
  4815. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4816. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4817. # self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4818. # "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4819. units = self.defaults["units"].lower()
  4820. self.plotcanvas.text_hud.text = \
  4821. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4822. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4823. self.mouse = [pos[0], pos[1]]
  4824. # if the mouse is moved and the LMB is clicked then the action is a selection
  4825. if self.event_is_dragging == 1 and event.button == 1:
  4826. self.delete_selection_shape()
  4827. if self.dx < 0:
  4828. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4829. face_color=self.defaults['global_alt_sel_fill'])
  4830. self.selection_type = False
  4831. elif self.dx >= 0:
  4832. self.draw_moving_selection_shape(self.pos, pos)
  4833. self.selection_type = True
  4834. else:
  4835. self.selection_type = None
  4836. else:
  4837. self.selection_type = None
  4838. # hover effect - enabled in Preferences -> General -> AppGUI Settings
  4839. if self.defaults['global_hover']:
  4840. for obj in self.collection.get_list():
  4841. try:
  4842. # select the object(s) only if it is enabled (plotted)
  4843. if obj.options['plot']:
  4844. if obj not in self.collection.get_selected():
  4845. poly_obj = Polygon(
  4846. [(obj.options['xmin'], obj.options['ymin']),
  4847. (obj.options['xmax'], obj.options['ymin']),
  4848. (obj.options['xmax'], obj.options['ymax']),
  4849. (obj.options['xmin'], obj.options['ymax'])]
  4850. )
  4851. if Point(pos).within(poly_obj):
  4852. if obj.isHovering is False:
  4853. obj.isHovering = True
  4854. obj.notHovering = True
  4855. # create the selection box around the selected object
  4856. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4857. else:
  4858. if obj.notHovering is True:
  4859. obj.notHovering = False
  4860. obj.isHovering = False
  4861. self.delete_hover_shape()
  4862. except Exception:
  4863. # the Exception here will happen if we try to select on screen and we have an
  4864. # newly (and empty) just created Geometry or Excellon object that do not have the
  4865. # xmin, xmax, ymin, ymax options.
  4866. # In this case poly_obj creation (see above) will fail
  4867. pass
  4868. except Exception as e:
  4869. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4870. self.ui.position_label.setText("")
  4871. # self.ui.rel_position_label.setText("")
  4872. self.mouse = None
  4873. def on_mouse_click_release_over_plot(self, event):
  4874. """
  4875. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4876. and has been registered in ''self.__init__()''.
  4877. :param event: contains information about the event.
  4878. :return:
  4879. """
  4880. if self.is_legacy is False:
  4881. event_pos = event.pos
  4882. right_button = 2
  4883. else:
  4884. event_pos = (event.xdata, event.ydata)
  4885. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4886. right_button = 3
  4887. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4888. if self.grid_status():
  4889. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4890. else:
  4891. pos = (pos_canvas[0], pos_canvas[1])
  4892. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4893. # canvas menu
  4894. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  4895. self.ui.popMenu.mouse_is_panning = False
  4896. self.cursor = QtGui.QCursor()
  4897. self.populate_cmenu_grids()
  4898. self.ui.popMenu.popup(self.cursor.pos())
  4899. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4900. # selection and then select a type of selection ("enclosing" or "touching")
  4901. if event.button == 1: # left click
  4902. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4903. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4904. if modifiers == QtCore.Qt.ShiftModifier:
  4905. # do not auto open the Project Tab
  4906. self.click_noproject = True
  4907. self.clipboard.setText(
  4908. self.defaults["global_point_clipboard_format"] %
  4909. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  4910. )
  4911. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  4912. return
  4913. if self.doubleclick is True:
  4914. self.doubleclick = False
  4915. if self.collection.get_selected():
  4916. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4917. if self.ui.splitter.sizes()[0] == 0:
  4918. self.ui.splitter.setSizes([1, 1])
  4919. try:
  4920. # delete the selection shape(S) as it may be in the way
  4921. self.delete_selection_shape()
  4922. self.delete_hover_shape()
  4923. except Exception as e:
  4924. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  4925. return
  4926. else:
  4927. # WORKAROUND for LEGACY MODE
  4928. if self.is_legacy is True:
  4929. # if there is no move on canvas then we have no dragging selection
  4930. if self.dx == 0 or self.dy == 0:
  4931. self.selection_type = None
  4932. if self.selection_type is not None:
  4933. try:
  4934. self.selection_area_handler(self.pos, pos, self.selection_type)
  4935. self.selection_type = None
  4936. except Exception as e:
  4937. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  4938. return
  4939. else:
  4940. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  4941. if key_modifier == QtCore.Qt.ShiftModifier:
  4942. mod_key = 'Shift'
  4943. elif key_modifier == QtCore.Qt.ControlModifier:
  4944. mod_key = 'Control'
  4945. else:
  4946. mod_key = None
  4947. try:
  4948. if self.command_active is None:
  4949. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  4950. # deselect, and if it's not selected then it will be selected
  4951. # If there is no active command (self.command_active is None) then we check if we clicked
  4952. # on a object by checking the bounding limits against mouse click position
  4953. if mod_key == self.defaults["global_mselect_key"]:
  4954. self.select_objects(key='multisel')
  4955. else:
  4956. # If there is no active command (self.command_active is None) then we check if
  4957. # we clicked on a object by checking the bounding limits against mouse click position
  4958. self.select_objects()
  4959. self.delete_hover_shape()
  4960. except Exception as e:
  4961. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  4962. return
  4963. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4964. """
  4965. :param start_pos: mouse position when the selection LMB click was done
  4966. :param end_pos: mouse position when the left mouse button is released
  4967. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4968. :return:
  4969. """
  4970. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4971. # delete previous selection shape
  4972. self.delete_selection_shape()
  4973. # make all objects inactive
  4974. self.collection.set_all_inactive()
  4975. for obj in self.collection.get_list():
  4976. try:
  4977. # select the object(s) only if it is enabled (plotted)
  4978. if obj.options['plot']:
  4979. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4980. (obj.options['xmax'], obj.options['ymin']),
  4981. (obj.options['xmax'], obj.options['ymax']),
  4982. (obj.options['xmin'], obj.options['ymax'])])
  4983. if sel_type is True:
  4984. if poly_obj.within(poly_selection):
  4985. # create the selection box around the selected object
  4986. if self.defaults['global_selection_shape'] is True:
  4987. self.draw_selection_shape(obj)
  4988. self.collection.set_active(obj.options['name'])
  4989. else:
  4990. if poly_selection.intersects(poly_obj):
  4991. # create the selection box around the selected object
  4992. if self.defaults['global_selection_shape'] is True:
  4993. self.draw_selection_shape(obj)
  4994. self.collection.set_active(obj.options['name'])
  4995. obj.selection_shape_drawn = True
  4996. except Exception as e:
  4997. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4998. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4999. # In this case poly_obj creation (see above) will fail
  5000. log.debug("App.selection_area_handler() --> %s" % str(e))
  5001. def select_objects(self, key=None):
  5002. """
  5003. Will select objects clicked on canvas
  5004. :param key: for future use in cumulative selection
  5005. :return:
  5006. """
  5007. # list where we store the overlapped objects under our mouse left click position
  5008. if key is None:
  5009. self.objects_under_the_click_list = []
  5010. # Populate the list with the overlapped objects on the click position
  5011. curr_x, curr_y = self.pos
  5012. for obj in self.all_objects_list:
  5013. # ScriptObject and DocumentObject objects can't be selected
  5014. if obj.kind == 'script' or obj.kind == 'document':
  5015. continue
  5016. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5017. continue
  5018. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5019. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5020. if obj.options['name'] not in self.objects_under_the_click_list:
  5021. if obj.options['plot']:
  5022. # add objects to the objects_under_the_click list only if the object is plotted
  5023. # (active and not disabled)
  5024. self.objects_under_the_click_list.append(obj.options['name'])
  5025. try:
  5026. if self.objects_under_the_click_list:
  5027. curr_sel_obj = self.collection.get_active()
  5028. # case when there is only an object under the click and we toggle it
  5029. if len(self.objects_under_the_click_list) == 1:
  5030. if curr_sel_obj is None:
  5031. self.collection.set_active(self.objects_under_the_click_list[0])
  5032. curr_sel_obj = self.collection.get_active()
  5033. # create the selection box around the selected object
  5034. if self.defaults['global_selection_shape'] is True:
  5035. self.draw_selection_shape(curr_sel_obj)
  5036. curr_sel_obj.selection_shape_drawn = True
  5037. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5038. self.collection.on_objects_selection(False)
  5039. self.delete_selection_shape()
  5040. curr_sel_obj.selection_shape_drawn = False
  5041. self.collection.set_active(self.objects_under_the_click_list[0])
  5042. curr_sel_obj = self.collection.get_active()
  5043. # create the selection box around the selected object
  5044. if self.defaults['global_selection_shape'] is True:
  5045. self.draw_selection_shape(curr_sel_obj)
  5046. curr_sel_obj.selection_shape_drawn = True
  5047. self.selected_message(curr_sel_obj=curr_sel_obj)
  5048. elif curr_sel_obj.selection_shape_drawn is False:
  5049. if self.defaults['global_selection_shape'] is True:
  5050. self.draw_selection_shape(curr_sel_obj)
  5051. curr_sel_obj.selection_shape_drawn = True
  5052. else:
  5053. self.collection.on_objects_selection(False)
  5054. self.delete_selection_shape()
  5055. if self.call_source != 'app':
  5056. self.call_source = 'app'
  5057. self.selected_message(curr_sel_obj=curr_sel_obj)
  5058. else:
  5059. # If there is no selected object
  5060. # make active the first element of the overlapped objects list
  5061. if self.collection.get_active() is None:
  5062. self.collection.set_active(self.objects_under_the_click_list[0])
  5063. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5064. name_sel_obj = self.collection.get_active().options['name']
  5065. # In case that there is a selected object but it is not in the overlapped object list
  5066. # make that object inactive and activate the first element in the overlapped object list
  5067. if name_sel_obj not in self.objects_under_the_click_list:
  5068. self.collection.set_inactive(name_sel_obj)
  5069. name_sel_obj = self.objects_under_the_click_list[0]
  5070. self.collection.set_active(name_sel_obj)
  5071. else:
  5072. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5073. self.collection.set_all_inactive()
  5074. self.collection.set_active(
  5075. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5076. curr_sel_obj = self.collection.get_active()
  5077. # delete the possible selection box around a possible selected object
  5078. self.delete_selection_shape()
  5079. curr_sel_obj.selection_shape_drawn = False
  5080. # create the selection box around the selected object
  5081. if self.defaults['global_selection_shape'] is True:
  5082. self.draw_selection_shape(curr_sel_obj)
  5083. curr_sel_obj.selection_shape_drawn = True
  5084. self.selected_message(curr_sel_obj=curr_sel_obj)
  5085. else:
  5086. # deselect everything
  5087. self.collection.on_objects_selection(False)
  5088. # delete the possible selection box around a possible selected object
  5089. self.delete_selection_shape()
  5090. for o in self.collection.get_list():
  5091. o.selection_shape_drawn = False
  5092. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5093. # only when working on App
  5094. if self.call_source == 'app':
  5095. if self.click_noproject is False:
  5096. # if the Tool Tab is in focus don't change focus to Project Tab
  5097. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5098. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5099. else:
  5100. # restore auto open the Project Tab
  5101. self.click_noproject = False
  5102. # delete any text in the status bar, implicitly the last object name that was selected
  5103. # self.inform.emit("")
  5104. else:
  5105. self.call_source = 'app'
  5106. except Exception as e:
  5107. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5108. def selected_message(self, curr_sel_obj):
  5109. if curr_sel_obj:
  5110. if curr_sel_obj.kind == 'gerber':
  5111. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5112. color='green',
  5113. name=str(curr_sel_obj.options['name']),
  5114. tx=_("selected"))
  5115. )
  5116. elif curr_sel_obj.kind == 'excellon':
  5117. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5118. color='brown',
  5119. name=str(curr_sel_obj.options['name']),
  5120. tx=_("selected"))
  5121. )
  5122. elif curr_sel_obj.kind == 'cncjob':
  5123. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5124. color='blue',
  5125. name=str(curr_sel_obj.options['name']),
  5126. tx=_("selected"))
  5127. )
  5128. elif curr_sel_obj.kind == 'geometry':
  5129. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5130. color='red',
  5131. name=str(curr_sel_obj.options['name']),
  5132. tx=_("selected"))
  5133. )
  5134. def delete_hover_shape(self):
  5135. self.hover_shapes.clear()
  5136. self.hover_shapes.redraw()
  5137. def draw_hover_shape(self, sel_obj, color=None):
  5138. """
  5139. :param sel_obj: The object for which the hover shape must be drawn
  5140. :param color: The color of the hover shape
  5141. :return: None
  5142. """
  5143. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5144. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5145. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5146. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5147. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5148. if self.defaults['units'].upper() == 'MM':
  5149. hover_rect = hover_rect.buffer(-0.1)
  5150. hover_rect = hover_rect.buffer(0.2)
  5151. else:
  5152. hover_rect = hover_rect.buffer(-0.00393)
  5153. hover_rect = hover_rect.buffer(0.00787)
  5154. # if color:
  5155. # face = Color(color)
  5156. # face.alpha = 0.2
  5157. # outline = Color(color, alpha=0.8)
  5158. # else:
  5159. # face = Color(self.defaults['global_sel_fill'])
  5160. # face.alpha = 0.2
  5161. # outline = self.defaults['global_sel_line']
  5162. if color:
  5163. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5164. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5165. else:
  5166. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5167. outline = self.defaults['global_sel_line']
  5168. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5169. if self.is_legacy is True:
  5170. self.hover_shapes.redraw()
  5171. def delete_selection_shape(self):
  5172. self.move_tool.sel_shapes.clear()
  5173. self.move_tool.sel_shapes.redraw()
  5174. def draw_selection_shape(self, sel_obj, color=None):
  5175. """
  5176. Will draw a selection shape around the selected object.
  5177. :param sel_obj: The object for which the selection shape must be drawn
  5178. :param color: The color for the selection shape.
  5179. :return: None
  5180. """
  5181. if sel_obj is None:
  5182. return
  5183. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5184. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5185. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5186. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5187. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5188. if self.defaults['units'].upper() == 'MM':
  5189. sel_rect = sel_rect.buffer(-0.1)
  5190. sel_rect = sel_rect.buffer(0.2)
  5191. else:
  5192. sel_rect = sel_rect.buffer(-0.00393)
  5193. sel_rect = sel_rect.buffer(0.00787)
  5194. if color:
  5195. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5196. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5197. else:
  5198. if self.is_legacy is False:
  5199. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5200. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5201. else:
  5202. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5203. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5204. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5205. color=outline,
  5206. face_color=face,
  5207. update=True,
  5208. layer=0,
  5209. tolerance=None))
  5210. if self.is_legacy is True:
  5211. self.move_tool.sel_shapes.redraw()
  5212. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5213. """
  5214. Will draw a selection shape when dragging mouse on canvas.
  5215. :param old_coords: Old coordinates
  5216. :param coords: New coordinates
  5217. :param kwargs: Keyword arguments
  5218. :return:
  5219. """
  5220. if 'color' in kwargs:
  5221. color = kwargs['color']
  5222. else:
  5223. color = self.defaults['global_sel_line']
  5224. if 'face_color' in kwargs:
  5225. face_color = kwargs['face_color']
  5226. else:
  5227. face_color = self.defaults['global_sel_fill']
  5228. if 'face_alpha' in kwargs:
  5229. face_alpha = kwargs['face_alpha']
  5230. else:
  5231. face_alpha = 0.3
  5232. x0, y0 = old_coords
  5233. x1, y1 = coords
  5234. pt1 = (x0, y0)
  5235. pt2 = (x1, y0)
  5236. pt3 = (x1, y1)
  5237. pt4 = (x0, y1)
  5238. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5239. # color_t = Color(face_color)
  5240. # color_t.alpha = face_alpha
  5241. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5242. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5243. layer=0, tolerance=None)
  5244. if self.is_legacy is True:
  5245. self.move_tool.sel_shapes.redraw()
  5246. def on_file_new_click(self):
  5247. """
  5248. Callback for menu item File -> New.
  5249. Executed on clicking the Menu -> File -> New Project
  5250. :return:
  5251. """
  5252. if self.collection.get_list() and self.should_we_save:
  5253. msgbox = QtWidgets.QMessageBox()
  5254. # msgbox.setText("<B>Save changes ...</B>")
  5255. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5256. "Creating a New project will delete them.\n"
  5257. "Do you want to Save the project?"))
  5258. msgbox.setWindowTitle(_("Save changes"))
  5259. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5260. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5261. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5262. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5263. msgbox.setDefaultButton(bt_yes)
  5264. msgbox.exec_()
  5265. response = msgbox.clickedButton()
  5266. if response == bt_yes:
  5267. self.on_file_saveprojectas()
  5268. elif response == bt_cancel:
  5269. return
  5270. elif response == bt_no:
  5271. self.on_file_new()
  5272. else:
  5273. self.on_file_new()
  5274. self.inform.emit('[success] %s...' % _("New Project created"))
  5275. def on_file_new(self, cli=None):
  5276. """
  5277. Returns the application to its startup state. This method is thread-safe.
  5278. :param cli: Boolean. If True this method was run from command line
  5279. :return: None
  5280. """
  5281. self.defaults.report_usage("on_file_new")
  5282. # Remove everything from memory
  5283. App.log.debug("on_file_new()")
  5284. # close any editor that might be open
  5285. if self.call_source != 'app':
  5286. self.editor2object(cleanup=True)
  5287. # ## EDITOR section
  5288. self.geo_editor = FlatCAMGeoEditor(self)
  5289. self.exc_editor = FlatCAMExcEditor(self)
  5290. self.grb_editor = FlatCAMGrbEditor(self)
  5291. # Clear pool
  5292. self.clear_pool()
  5293. for obj in self.collection.get_list():
  5294. # delete shapes left drawn from mark shape_collections, if any
  5295. if isinstance(obj, GerberObject):
  5296. try:
  5297. for el in obj.mark_shapes:
  5298. obj.mark_shapes[el].clear(update=True)
  5299. obj.mark_shapes[el].enabled = False
  5300. del el
  5301. except AttributeError:
  5302. pass
  5303. # also delete annotation shapes, if any
  5304. elif isinstance(obj, CNCJobObject):
  5305. try:
  5306. obj.text_col.enabled = False
  5307. del obj.text_col
  5308. obj.annotation.clear(update=True)
  5309. del obj.annotation
  5310. except AttributeError:
  5311. pass
  5312. # delete the exclusion areas
  5313. self.exc_areas.clear_shapes()
  5314. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5315. self.shell.init_tcl()
  5316. # delete any selection shape on canvas
  5317. self.delete_selection_shape()
  5318. # delete all FlatCAM objects
  5319. self.collection.delete_all()
  5320. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5321. self.setup_component_editor()
  5322. # Clear project filename
  5323. self.project_filename = None
  5324. # Load the application defaults
  5325. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5326. # Re-fresh project options
  5327. self.on_options_app2project()
  5328. # Init FlatCAMTools
  5329. self.init_tools()
  5330. # Try to close all tabs in the PlotArea but only if the AppGUI is active (CLI is None)
  5331. if cli is None:
  5332. # we need to go in reverse because once we remove a tab then the index changes
  5333. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5334. # and so on. Therefore the deletion should be done in reverse
  5335. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5336. for index in range(wdg_count, -1, -1):
  5337. try:
  5338. self.ui.plot_tab_area.closeTab(index)
  5339. except Exception as e:
  5340. log.debug("App.on_file_new() --> %s" % str(e))
  5341. # # And then add again the Plot Area
  5342. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5343. self.ui.plot_tab_area.protectTab(0)
  5344. # take the focus of the Notebook on Project Tab.
  5345. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5346. self.set_ui_title(name=_("New Project - Not saved"))
  5347. def obj_properties(self):
  5348. """
  5349. Will launch the object Properties Tool
  5350. :return:
  5351. """
  5352. self.defaults.report_usage("obj_properties()")
  5353. self.properties_tool.run(toggle=False)
  5354. def on_project_context_save(self):
  5355. """
  5356. Wrapper, will save the object function of it's type
  5357. :return:
  5358. """
  5359. obj = self.collection.get_active()
  5360. if type(obj) == GeometryObject:
  5361. self.on_file_exportdxf()
  5362. elif type(obj) == ExcellonObject:
  5363. self.on_file_saveexcellon()
  5364. elif type(obj) == CNCJobObject:
  5365. obj.on_exportgcode_button_click()
  5366. elif type(obj) == GerberObject:
  5367. self.on_file_savegerber()
  5368. elif type(obj) == ScriptObject:
  5369. self.on_file_savescript()
  5370. elif type(obj) == DocumentObject:
  5371. self.on_file_savedocument()
  5372. def obj_move(self):
  5373. """
  5374. Callback for the Move menu entry in various Context Menu's.
  5375. :return:
  5376. """
  5377. self.defaults.report_usage("obj_move()")
  5378. self.move_tool.run(toggle=False)
  5379. def on_fileopengerber(self, signal, name=None):
  5380. """
  5381. File menu callback for opening a Gerber.
  5382. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5383. :param name:
  5384. :return: None
  5385. """
  5386. self.defaults.report_usage("on_fileopengerber")
  5387. App.log.debug("on_fileopengerber()")
  5388. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  5389. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  5390. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  5391. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  5392. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5393. "*.mil);;" \
  5394. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5395. "Allegro Files (*.art);;" \
  5396. "Mentor Files (*.pho *.gdo);;" \
  5397. "All Files (*.*)"
  5398. if name is None:
  5399. try:
  5400. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5401. directory=self.get_last_folder(),
  5402. filter=_filter_)
  5403. except TypeError:
  5404. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5405. filenames = [str(filename) for filename in filenames]
  5406. else:
  5407. filenames = [name]
  5408. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5409. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5410. _("Opening Gerber file.")),
  5411. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5412. color=QtGui.QColor("gray"))
  5413. if len(filenames) == 0:
  5414. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5415. else:
  5416. for filename in filenames:
  5417. if filename != '':
  5418. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5419. def on_fileopenexcellon(self, signal, name=None):
  5420. """
  5421. File menu callback for opening an Excellon file.
  5422. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5423. :param name:
  5424. :return: None
  5425. """
  5426. self.defaults.report_usage("on_fileopenexcellon")
  5427. App.log.debug("on_fileopenexcellon()")
  5428. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5429. "All Files (*.*)"
  5430. if name is None:
  5431. try:
  5432. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5433. directory=self.get_last_folder(),
  5434. filter=_filter_)
  5435. except TypeError:
  5436. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5437. filenames = [str(filename) for filename in filenames]
  5438. else:
  5439. filenames = [str(name)]
  5440. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5441. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5442. _("Opening Excellon file.")),
  5443. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5444. color=QtGui.QColor("gray"))
  5445. if len(filenames) == 0:
  5446. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5447. else:
  5448. for filename in filenames:
  5449. if filename != '':
  5450. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5451. def on_fileopengcode(self, signal, name=None):
  5452. """
  5453. File menu call back for opening gcode.
  5454. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5455. :param name:
  5456. :return:
  5457. """
  5458. self.defaults.report_usage("on_fileopengcode")
  5459. App.log.debug("on_fileopengcode()")
  5460. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5461. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5462. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5463. "All Files (*.*)"
  5464. if name is None:
  5465. try:
  5466. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5467. directory=self.get_last_folder(),
  5468. filter=_filter_)
  5469. except TypeError:
  5470. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5471. filenames = [str(filename) for filename in filenames]
  5472. else:
  5473. filenames = [name]
  5474. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5475. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5476. _("Opening G-Code file.")),
  5477. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5478. color=QtGui.QColor("gray"))
  5479. if len(filenames) == 0:
  5480. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5481. else:
  5482. for filename in filenames:
  5483. if filename != '':
  5484. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5485. def on_file_openproject(self, signal):
  5486. """
  5487. File menu callback for opening a project.
  5488. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5489. :return: None
  5490. """
  5491. self.defaults.report_usage("on_file_openproject")
  5492. App.log.debug("on_file_openproject()")
  5493. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5494. try:
  5495. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5496. directory=self.get_last_folder(), filter=_filter_)
  5497. except TypeError:
  5498. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5499. # The Qt methods above will return a QString which can cause problems later.
  5500. # So far json.dump() will fail to serialize it.
  5501. # TODO: Improve the serialization methods and remove this fix.
  5502. filename = str(filename)
  5503. if filename == "":
  5504. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5505. else:
  5506. # self.worker_task.emit({'fcn': self.open_project,
  5507. # 'params': [filename]})
  5508. # The above was failing because open_project() is not
  5509. # thread safe. The new_project()
  5510. self.open_project(filename)
  5511. def on_fileopenhpgl2(self, signal, name=None):
  5512. """
  5513. File menu callback for opening a HPGL2.
  5514. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5515. :param name:
  5516. :return: None
  5517. """
  5518. self.defaults.report_usage("on_fileopenhpgl2")
  5519. App.log.debug("on_fileopenhpgl2()")
  5520. _filter_ = "HPGL2 Files (*.plt);;" \
  5521. "All Files (*.*)"
  5522. if name is None:
  5523. try:
  5524. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5525. directory=self.get_last_folder(),
  5526. filter=_filter_)
  5527. except TypeError:
  5528. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5529. filenames = [str(filename) for filename in filenames]
  5530. else:
  5531. filenames = [name]
  5532. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5533. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5534. _("Opening HPGL2 file.")),
  5535. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5536. color=QtGui.QColor("gray"))
  5537. if len(filenames) == 0:
  5538. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5539. else:
  5540. for filename in filenames:
  5541. if filename != '':
  5542. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5543. def on_file_openconfig(self, signal):
  5544. """
  5545. File menu callback for opening a config file.
  5546. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5547. :return: None
  5548. """
  5549. self.defaults.report_usage("on_file_openconfig")
  5550. App.log.debug("on_file_openconfig()")
  5551. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5552. try:
  5553. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5554. directory=self.data_path, filter=_filter_)
  5555. except TypeError:
  5556. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5557. filter=_filter_)
  5558. if filename == "":
  5559. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5560. else:
  5561. self.open_config_file(filename)
  5562. def on_file_exportsvg(self):
  5563. """
  5564. Callback for menu item File->Export SVG.
  5565. :return: None
  5566. """
  5567. self.defaults.report_usage("on_file_exportsvg")
  5568. App.log.debug("on_file_exportsvg()")
  5569. obj = self.collection.get_active()
  5570. if obj is None:
  5571. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5572. msg = _("Please Select a Geometry object to export")
  5573. msgbox = QtWidgets.QMessageBox()
  5574. msgbox.setInformativeText(msg)
  5575. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5576. msgbox.setDefaultButton(bt_ok)
  5577. msgbox.exec_()
  5578. return
  5579. # Check for more compatible types and add as required
  5580. if (not isinstance(obj, GeometryObject)
  5581. and not isinstance(obj, GerberObject)
  5582. and not isinstance(obj, CNCJobObject)
  5583. and not isinstance(obj, ExcellonObject)):
  5584. msg = '[ERROR_NOTCL] %s' % \
  5585. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5586. msgbox = QtWidgets.QMessageBox()
  5587. msgbox.setInformativeText(msg)
  5588. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5589. msgbox.setDefaultButton(bt_ok)
  5590. msgbox.exec_()
  5591. return
  5592. name = obj.options["name"]
  5593. _filter = "SVG File (*.svg);;All Files (*.*)"
  5594. try:
  5595. filename, _f = FCFileSaveDialog.get_saved_filename(
  5596. caption=_("Export SVG"),
  5597. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5598. filter=_filter)
  5599. except TypeError:
  5600. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  5601. filename = str(filename)
  5602. if filename == "":
  5603. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  5604. return
  5605. else:
  5606. self.export_svg(name, filename)
  5607. if self.defaults["global_open_style"] is False:
  5608. self.file_opened.emit("SVG", filename)
  5609. self.file_saved.emit("SVG", filename)
  5610. def on_file_exportpng(self):
  5611. self.defaults.report_usage("on_file_exportpng")
  5612. App.log.debug("on_file_exportpng()")
  5613. self.date = str(datetime.today()).rpartition('.')[0]
  5614. self.date = ''.join(c for c in self.date if c not in ':-')
  5615. self.date = self.date.replace(' ', '_')
  5616. if self.is_legacy is False:
  5617. image = _screenshot()
  5618. data = np.asarray(image)
  5619. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5620. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5621. return
  5622. filter_ = "PNG File (*.png);;All Files (*.*)"
  5623. try:
  5624. filename, _f = FCFileSaveDialog.get_saved_filename(
  5625. caption=_("Export PNG Image"),
  5626. directory=self.get_last_save_folder() + '/png_' + self.date,
  5627. filter=filter_)
  5628. except TypeError:
  5629. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  5630. filename = str(filename)
  5631. if filename == "":
  5632. self.inform.emit(_("Cancelled."))
  5633. return
  5634. else:
  5635. if self.is_legacy is False:
  5636. write_png(filename, data)
  5637. else:
  5638. self.plotcanvas.figure.savefig(filename)
  5639. if self.defaults["global_open_style"] is False:
  5640. self.file_opened.emit("png", filename)
  5641. self.file_saved.emit("png", filename)
  5642. def on_file_savegerber(self):
  5643. """
  5644. Callback for menu item in Project context menu.
  5645. :return: None
  5646. """
  5647. self.defaults.report_usage("on_file_savegerber")
  5648. App.log.debug("on_file_savegerber()")
  5649. obj = self.collection.get_active()
  5650. if obj is None:
  5651. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5652. return
  5653. # Check for more compatible types and add as required
  5654. if not isinstance(obj, GerberObject):
  5655. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5656. return
  5657. name = self.collection.get_active().options["name"]
  5658. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5659. try:
  5660. filename, _f = FCFileSaveDialog.get_saved_filename(
  5661. caption="Save Gerber source file",
  5662. directory=self.get_last_save_folder() + '/' + name,
  5663. filter=_filter)
  5664. except TypeError:
  5665. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  5666. filename = str(filename)
  5667. if filename == "":
  5668. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5669. return
  5670. else:
  5671. self.save_source_file(name, filename)
  5672. if self.defaults["global_open_style"] is False:
  5673. self.file_opened.emit("Gerber", filename)
  5674. self.file_saved.emit("Gerber", filename)
  5675. def on_file_savescript(self):
  5676. """
  5677. Callback for menu item in Project context menu.
  5678. :return: None
  5679. """
  5680. self.defaults.report_usage("on_file_savescript")
  5681. App.log.debug("on_file_savescript()")
  5682. obj = self.collection.get_active()
  5683. if obj is None:
  5684. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5685. return
  5686. # Check for more compatible types and add as required
  5687. if not isinstance(obj, ScriptObject):
  5688. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5689. return
  5690. name = self.collection.get_active().options["name"]
  5691. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5692. try:
  5693. filename, _f = FCFileSaveDialog.get_saved_filename(
  5694. caption="Save Script source file",
  5695. directory=self.get_last_save_folder() + '/' + name,
  5696. filter=_filter)
  5697. except TypeError:
  5698. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  5699. filename = str(filename)
  5700. if filename == "":
  5701. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5702. return
  5703. else:
  5704. self.save_source_file(name, filename)
  5705. if self.defaults["global_open_style"] is False:
  5706. self.file_opened.emit("Script", filename)
  5707. self.file_saved.emit("Script", filename)
  5708. def on_file_savedocument(self):
  5709. """
  5710. Callback for menu item in Project context menu.
  5711. :return: None
  5712. """
  5713. self.defaults.report_usage("on_file_savedocument")
  5714. App.log.debug("on_file_savedocument()")
  5715. obj = self.collection.get_active()
  5716. if obj is None:
  5717. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5718. return
  5719. # Check for more compatible types and add as required
  5720. if not isinstance(obj, ScriptObject):
  5721. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5722. return
  5723. name = self.collection.get_active().options["name"]
  5724. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5725. try:
  5726. filename, _f = FCFileSaveDialog.get_saved_filename(
  5727. caption="Save Document source file",
  5728. directory=self.get_last_save_folder() + '/' + name,
  5729. filter=_filter)
  5730. except TypeError:
  5731. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  5732. filename = str(filename)
  5733. if filename == "":
  5734. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5735. return
  5736. else:
  5737. self.save_source_file(name, filename)
  5738. if self.defaults["global_open_style"] is False:
  5739. self.file_opened.emit("Document", filename)
  5740. self.file_saved.emit("Document", filename)
  5741. def on_file_saveexcellon(self):
  5742. """
  5743. Callback for menu item in project context menu.
  5744. :return: None
  5745. """
  5746. self.defaults.report_usage("on_file_saveexcellon")
  5747. App.log.debug("on_file_saveexcellon()")
  5748. obj = self.collection.get_active()
  5749. if obj is None:
  5750. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5751. return
  5752. # Check for more compatible types and add as required
  5753. if not isinstance(obj, ExcellonObject):
  5754. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5755. return
  5756. name = self.collection.get_active().options["name"]
  5757. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5758. try:
  5759. filename, _f = FCFileSaveDialog.get_saved_filename(
  5760. caption=_("Save Excellon source file"),
  5761. directory=self.get_last_save_folder() + '/' + name,
  5762. filter=_filter)
  5763. except TypeError:
  5764. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  5765. filename = str(filename)
  5766. if filename == "":
  5767. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5768. return
  5769. else:
  5770. self.save_source_file(name, filename)
  5771. if self.defaults["global_open_style"] is False:
  5772. self.file_opened.emit("Excellon", filename)
  5773. self.file_saved.emit("Excellon", filename)
  5774. def on_file_exportexcellon(self):
  5775. """
  5776. Callback for menu item File->Export->Excellon.
  5777. :return: None
  5778. """
  5779. self.defaults.report_usage("on_file_exportexcellon")
  5780. App.log.debug("on_file_exportexcellon()")
  5781. obj = self.collection.get_active()
  5782. if obj is None:
  5783. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5784. return
  5785. # Check for more compatible types and add as required
  5786. if not isinstance(obj, ExcellonObject):
  5787. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5788. return
  5789. name = self.collection.get_active().options["name"]
  5790. _filter = self.defaults["excellon_save_filters"]
  5791. try:
  5792. filename, _f = FCFileSaveDialog.get_saved_filename(
  5793. caption=_("Export Excellon"),
  5794. directory=self.get_last_save_folder() + '/' + name,
  5795. filter=_filter)
  5796. except TypeError:
  5797. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  5798. filename = str(filename)
  5799. if filename == "":
  5800. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5801. return
  5802. else:
  5803. used_extension = filename.rpartition('.')[2]
  5804. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5805. self.export_excellon(name, filename)
  5806. if self.defaults["global_open_style"] is False:
  5807. self.file_opened.emit("Excellon", filename)
  5808. self.file_saved.emit("Excellon", filename)
  5809. def on_file_exportgerber(self):
  5810. """
  5811. Callback for menu item File->Export->Gerber.
  5812. :return: None
  5813. """
  5814. self.defaults.report_usage("on_file_exportgerber")
  5815. App.log.debug("on_file_exportgerber()")
  5816. obj = self.collection.get_active()
  5817. if obj is None:
  5818. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5819. return
  5820. # Check for more compatible types and add as required
  5821. if not isinstance(obj, GerberObject):
  5822. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5823. return
  5824. name = self.collection.get_active().options["name"]
  5825. _filter_ = self.defaults['gerber_save_filters']
  5826. try:
  5827. filename, _f = FCFileSaveDialog.get_saved_filename(
  5828. caption=_("Export Gerber"),
  5829. directory=self.get_last_save_folder() + '/' + name,
  5830. filter=_filter_)
  5831. except TypeError:
  5832. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  5833. filename = str(filename)
  5834. if filename == "":
  5835. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5836. return
  5837. else:
  5838. used_extension = filename.rpartition('.')[2]
  5839. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5840. self.export_gerber(name, filename)
  5841. if self.defaults["global_open_style"] is False:
  5842. self.file_opened.emit("Gerber", filename)
  5843. self.file_saved.emit("Gerber", filename)
  5844. def on_file_exportdxf(self):
  5845. """
  5846. Callback for menu item File->Export DXF.
  5847. :return: None
  5848. """
  5849. self.defaults.report_usage("on_file_exportdxf")
  5850. App.log.debug("on_file_exportdxf()")
  5851. obj = self.collection.get_active()
  5852. if obj is None:
  5853. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5854. msg = _("Please Select a Geometry object to export")
  5855. msgbox = QtWidgets.QMessageBox()
  5856. msgbox.setInformativeText(msg)
  5857. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5858. msgbox.setDefaultButton(bt_ok)
  5859. msgbox.exec_()
  5860. return
  5861. # Check for more compatible types and add as required
  5862. if not isinstance(obj, GeometryObject):
  5863. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5864. msgbox = QtWidgets.QMessageBox()
  5865. msgbox.setInformativeText(msg)
  5866. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5867. msgbox.setDefaultButton(bt_ok)
  5868. msgbox.exec_()
  5869. return
  5870. name = self.collection.get_active().options["name"]
  5871. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5872. try:
  5873. filename, _f = FCFileSaveDialog.get_saved_filename(
  5874. caption=_("Export DXF"),
  5875. directory=self.get_last_save_folder() + '/' + name,
  5876. filter=_filter_)
  5877. except TypeError:
  5878. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  5879. filename = str(filename)
  5880. if filename == "":
  5881. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5882. return
  5883. else:
  5884. self.export_dxf(name, filename)
  5885. if self.defaults["global_open_style"] is False:
  5886. self.file_opened.emit("DXF", filename)
  5887. self.file_saved.emit("DXF", filename)
  5888. def on_file_importsvg(self, type_of_obj):
  5889. """
  5890. Callback for menu item File->Import SVG.
  5891. :param type_of_obj: to import the SVG as Geometry or as Gerber
  5892. :type type_of_obj: str
  5893. :return: None
  5894. """
  5895. self.defaults.report_usage("on_file_importsvg")
  5896. App.log.debug("on_file_importsvg()")
  5897. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  5898. try:
  5899. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5900. directory=self.get_last_folder(), filter=_filter_)
  5901. except TypeError:
  5902. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  5903. filter=_filter_)
  5904. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5905. type_of_obj = "geometry"
  5906. filenames = [str(filename) for filename in filenames]
  5907. if len(filenames) == 0:
  5908. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5909. else:
  5910. for filename in filenames:
  5911. if filename != '':
  5912. self.worker_task.emit({'fcn': self.import_svg,
  5913. 'params': [filename, type_of_obj]})
  5914. def on_file_importdxf(self, type_of_obj):
  5915. """
  5916. Callback for menu item File->Import DXF.
  5917. :param type_of_obj: to import the DXF as Geometry or as Gerber
  5918. :type type_of_obj: str
  5919. :return: None
  5920. """
  5921. self.defaults.report_usage("on_file_importdxf")
  5922. App.log.debug("on_file_importdxf()")
  5923. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  5924. try:
  5925. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5926. directory=self.get_last_folder(),
  5927. filter=_filter_)
  5928. except TypeError:
  5929. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  5930. filter=_filter_)
  5931. if type_of_obj != "geometry" and type_of_obj != "gerber":
  5932. type_of_obj = "geometry"
  5933. filenames = [str(filename) for filename in filenames]
  5934. if len(filenames) == 0:
  5935. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5936. else:
  5937. for filename in filenames:
  5938. if filename != '':
  5939. self.worker_task.emit({'fcn': self.import_dxf,
  5940. 'params': [filename, type_of_obj]})
  5941. # ###############################################################################################################
  5942. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  5943. # ###############################################################################################################
  5944. def init_code_editor(self, name):
  5945. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  5946. # add the tab if it was closed
  5947. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  5948. self.text_editor_tab.setObjectName('text_editor_tab')
  5949. # delete the absolute and relative position and messages in the infobar
  5950. self.ui.position_label.setText("")
  5951. # self.ui.rel_position_label.setText("")
  5952. # first clear previous text in text editor (if any)
  5953. self.text_editor_tab.code_editor.clear()
  5954. self.text_editor_tab.code_editor.setReadOnly(False)
  5955. self.toggle_codeeditor = True
  5956. self.text_editor_tab.code_editor.completer_enable = False
  5957. self.text_editor_tab.buttonRun.hide()
  5958. # make sure to keep a reference to the code editor
  5959. self.reference_code_editor = self.text_editor_tab.code_editor
  5960. # Switch plot_area to CNCJob tab
  5961. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  5962. def on_view_source(self):
  5963. """
  5964. Called when the user wants to see the source file of the selected object
  5965. :return:
  5966. """
  5967. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  5968. self.proc_container.view.set_busy(_("Loading..."))
  5969. try:
  5970. obj = self.collection.get_active()
  5971. except Exception as e:
  5972. log.debug("App.on_view_source() --> %s" % str(e))
  5973. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5974. return 'fail'
  5975. if obj is None:
  5976. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  5977. return 'fail'
  5978. flt = "All Files (*.*)"
  5979. if obj.kind == 'gerber':
  5980. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5981. elif obj.kind == 'excellon':
  5982. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5983. elif obj.kind == 'cncjob':
  5984. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  5985. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  5986. # add the tab if it was closed
  5987. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  5988. self.source_editor_tab.setObjectName('source_editor_tab')
  5989. # delete the absolute and relative position and messages in the infobar
  5990. self.ui.position_label.setText("")
  5991. # self.ui.rel_position_label.setText("")
  5992. # first clear previous text in text editor (if any)
  5993. self.source_editor_tab.code_editor.clear()
  5994. self.source_editor_tab.code_editor.setReadOnly(False)
  5995. self.source_editor_tab.code_editor.completer_enable = False
  5996. self.source_editor_tab.buttonRun.hide()
  5997. # Switch plot_area to CNCJob tab
  5998. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  5999. try:
  6000. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6001. except TypeError:
  6002. pass
  6003. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6004. try:
  6005. self.source_editor_tab.buttonSave.clicked.disconnect()
  6006. except TypeError:
  6007. pass
  6008. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6009. # then append the text from GCode to the text editor
  6010. if obj.kind == 'cncjob':
  6011. try:
  6012. file = obj.export_gcode(
  6013. preamble=self.defaults["cncjob_prepend"],
  6014. postamble=self.defaults["cncjob_append"],
  6015. to_file=True)
  6016. if file == 'fail':
  6017. return 'fail'
  6018. except AttributeError:
  6019. self.inform.emit('[WARNING_NOTCL] %s' %
  6020. _("There is no selected object for which to see it's source file code."))
  6021. return 'fail'
  6022. else:
  6023. try:
  6024. file = StringIO(obj.source_file)
  6025. except (AttributeError, TypeError):
  6026. self.inform.emit('[WARNING_NOTCL] %s' %
  6027. _("There is no selected object for which to see it's source file code."))
  6028. return 'fail'
  6029. self.source_editor_tab.t_frame.hide()
  6030. try:
  6031. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6032. # for line in file:
  6033. # QtWidgets.QApplication.processEvents()
  6034. # proc_line = str(line).strip('\n')
  6035. # self.source_editor_tab.code_editor.append(proc_line)
  6036. except Exception as e:
  6037. log.debug('App.on_view_source() -->%s' % str(e))
  6038. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6039. return
  6040. self.source_editor_tab.handleTextChanged()
  6041. self.source_editor_tab.t_frame.show()
  6042. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6043. self.proc_container.view.set_idle()
  6044. # self.ui.show()
  6045. def on_toggle_code_editor(self):
  6046. self.defaults.report_usage("on_toggle_code_editor()")
  6047. if self.toggle_codeeditor is False:
  6048. self.init_code_editor(name=_("Code Editor"))
  6049. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6050. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6051. self.text_editor_tab.buttonSave.clicked.disconnect()
  6052. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6053. else:
  6054. for idx in range(self.ui.plot_tab_area.count()):
  6055. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6056. self.ui.plot_tab_area.closeTab(idx)
  6057. break
  6058. self.toggle_codeeditor = False
  6059. def on_code_editor_close(self):
  6060. self.toggle_codeeditor = False
  6061. def goto_text_line(self):
  6062. """
  6063. Will scroll a text to the specified text line.
  6064. :return: None
  6065. """
  6066. dia_box = Dialog_box(title=_("Go to Line ..."),
  6067. label=_("Line:"),
  6068. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6069. initial_text='')
  6070. try:
  6071. line = int(dia_box.location) - 1
  6072. except (ValueError, TypeError):
  6073. line = 0
  6074. if dia_box.ok:
  6075. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6076. # at the top of the window
  6077. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6078. # get the document() of the TextEditor
  6079. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6080. # create a Text Cursor based on the searched line
  6081. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6082. # set cursor of the code editor with the cursor at the searcehd line
  6083. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6084. def on_filenewscript(self, silent=False):
  6085. """
  6086. Will create a new script file and open it in the Code Editor
  6087. :param silent: if True will not display status messages
  6088. :return: None
  6089. """
  6090. if silent is False:
  6091. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6092. # delete the absolute and relative position and messages in the infobar
  6093. self.ui.position_label.setText("")
  6094. # self.ui.rel_position_label.setText("")
  6095. self.app_obj.new_script_object()
  6096. # script_text = script_obj.source_file
  6097. #
  6098. # self.proc_container.view.set_busy(_("Loading..."))
  6099. # script_obj.script_editor_tab.t_frame.hide()
  6100. #
  6101. # script_obj.script_editor_tab.t_frame.show()
  6102. # self.proc_container.view.set_idle()
  6103. def on_fileopenscript(self, name=None, silent=False):
  6104. """
  6105. Will open a Tcl script file into the Code Editor
  6106. :param silent: if True will not display status messages
  6107. :param name: name of a Tcl script file to open
  6108. :return: None
  6109. """
  6110. self.defaults.report_usage("on_fileopenscript")
  6111. App.log.debug("on_fileopenscript()")
  6112. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6113. "All Files (*.*)"
  6114. if name:
  6115. filenames = [name]
  6116. else:
  6117. try:
  6118. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6119. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6120. except TypeError:
  6121. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6122. if len(filenames) == 0:
  6123. if silent is False:
  6124. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6125. else:
  6126. for filename in filenames:
  6127. if filename != '':
  6128. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6129. def on_fileopenscript_example(self, name=None, silent=False):
  6130. """
  6131. Will open a Tcl script file into the Code Editor
  6132. :param silent: if True will not display status messages
  6133. :param name: name of a Tcl script file to open
  6134. :return:
  6135. """
  6136. self.defaults.report_usage("on_fileopenscript_example")
  6137. log.debug("on_fileopenscript_example()")
  6138. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6139. "All Files (*.*)"
  6140. # test if the app was frozen and choose the path for the configuration file
  6141. if getattr(sys, "frozen", False) is True:
  6142. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6143. else:
  6144. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6145. if name:
  6146. filenames = [name]
  6147. else:
  6148. try:
  6149. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6150. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6151. except TypeError:
  6152. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6153. if len(filenames) == 0:
  6154. if silent is False:
  6155. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6156. else:
  6157. for filename in filenames:
  6158. if filename != '':
  6159. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6160. def on_filerunscript(self, name=None, silent=False):
  6161. """
  6162. File menu callback for loading and running a TCL script.
  6163. :param silent: if True will not display status messages
  6164. :param name: name of a Tcl script file to be run by FlatCAM
  6165. :return: None
  6166. """
  6167. self.defaults.report_usage("on_filerunscript")
  6168. App.log.debug("on_file_runscript()")
  6169. if name:
  6170. filename = name
  6171. if self.cmd_line_headless != 1:
  6172. self.splash.showMessage('%s: %ssec\n%s' %
  6173. (_("Canvas initialization started.\n"
  6174. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6175. _("Executing ScriptObject file.")
  6176. ),
  6177. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6178. color=QtGui.QColor("gray"))
  6179. else:
  6180. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6181. "All Files (*.*)"
  6182. try:
  6183. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6184. directory=self.get_last_folder(), filter=_filter_)
  6185. except TypeError:
  6186. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6187. # The Qt methods above will return a QString which can cause problems later.
  6188. # So far json.dump() will fail to serialize it.
  6189. filename = str(filename)
  6190. if filename == "":
  6191. if silent is False:
  6192. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6193. else:
  6194. if self.cmd_line_headless != 1:
  6195. if self.ui.shell_dock.isHidden():
  6196. self.ui.shell_dock.show()
  6197. try:
  6198. with open(filename, "r") as tcl_script:
  6199. cmd_line_shellfile_content = tcl_script.read()
  6200. if self.cmd_line_headless != 1:
  6201. self.shell.exec_command(cmd_line_shellfile_content)
  6202. else:
  6203. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6204. if silent is False:
  6205. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6206. except Exception as e:
  6207. log.debug("App.on_filerunscript() -> %s" % str(e))
  6208. sys.exit(2)
  6209. def on_file_saveproject(self, silent=False):
  6210. """
  6211. Callback for menu item File->Save Project. Saves the project to
  6212. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6213. if set to None. The project is saved by calling ``self.save_project()``.
  6214. :param silent: if True will not display status messages
  6215. :return: None
  6216. """
  6217. self.defaults.report_usage("on_file_saveproject")
  6218. if self.project_filename is None:
  6219. self.on_file_saveprojectas()
  6220. else:
  6221. self.worker_task.emit({'fcn': self.save_project,
  6222. 'params': [self.project_filename, silent]})
  6223. if self.defaults["global_open_style"] is False:
  6224. self.file_opened.emit("project", self.project_filename)
  6225. self.file_saved.emit("project", self.project_filename)
  6226. self.set_ui_title(name=self.project_filename)
  6227. self.should_we_save = False
  6228. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6229. """
  6230. Callback for menu item File->Save Project As... Opens a file
  6231. chooser and saves the project to the given file via
  6232. ``self.save_project()``.
  6233. :param make_copy if to be create a copy of the project; boolean
  6234. :param use_thread: if to be run in a separate thread; boolean
  6235. :param quit_action: if to be followed by quiting the application; boolean
  6236. :return: None
  6237. """
  6238. self.defaults.report_usage("on_file_saveprojectas")
  6239. self.date = str(datetime.today()).rpartition('.')[0]
  6240. self.date = ''.join(c for c in self.date if c not in ':-')
  6241. self.date = self.date.replace(' ', '_')
  6242. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6243. try:
  6244. filename, _f = FCFileSaveDialog.get_saved_filename(
  6245. caption=_("Save Project As ..."),
  6246. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6247. proj=_("Project")),
  6248. filter=filter_
  6249. )
  6250. except TypeError:
  6251. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  6252. filename = str(filename)
  6253. if filename == '':
  6254. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6255. return
  6256. if use_thread is True:
  6257. self.worker_task.emit({'fcn': self.save_project,
  6258. 'params': [filename, quit_action]})
  6259. else:
  6260. self.save_project(filename, quit_action)
  6261. # self.save_project(filename)
  6262. if self.defaults["global_open_style"] is False:
  6263. self.file_opened.emit("project", filename)
  6264. self.file_saved.emit("project", filename)
  6265. if not make_copy:
  6266. self.project_filename = filename
  6267. self.set_ui_title(name=self.project_filename)
  6268. self.should_we_save = False
  6269. def on_file_save_objects_pdf(self, use_thread=True):
  6270. self.date = str(datetime.today()).rpartition('.')[0]
  6271. self.date = ''.join(c for c in self.date if c not in ':-')
  6272. self.date = self.date.replace(' ', '_')
  6273. try:
  6274. obj_selection = self.collection.get_selected()
  6275. if len(obj_selection) == 1:
  6276. obj_name = str(obj_selection[0].options['name'])
  6277. else:
  6278. obj_name = _("FlatCAM objects print")
  6279. except AttributeError as err:
  6280. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6281. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6282. return
  6283. if not obj_selection:
  6284. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6285. return
  6286. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6287. try:
  6288. filename, _f = FCFileSaveDialog.get_saved_filename(
  6289. caption=_("Save Object as PDF ..."),
  6290. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6291. obj_name=obj_name,
  6292. date=self.date),
  6293. filter=filter_
  6294. )
  6295. except TypeError:
  6296. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  6297. filename = str(filename)
  6298. if filename == '':
  6299. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6300. return
  6301. if use_thread is True:
  6302. self.proc_container.new(_("Printing PDF ... Please wait."))
  6303. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6304. else:
  6305. self.save_pdf(filename, obj_selection)
  6306. # self.save_project(filename)
  6307. if self.defaults["global_open_style"] is False:
  6308. self.file_opened.emit("pdf", filename)
  6309. self.file_saved.emit("pdf", filename)
  6310. def save_pdf(self, file_name, obj_selection):
  6311. p_size = self.defaults['global_workspaceT']
  6312. orientation = self.defaults['global_workspace_orientation']
  6313. color = 'black'
  6314. transparency_level = 1.0
  6315. self.pagesize = {}
  6316. self.pagesize.update(
  6317. {
  6318. 'Bounds': None,
  6319. 'A0': (841 * mm, 1189 * mm),
  6320. 'A1': (594 * mm, 841 * mm),
  6321. 'A2': (420 * mm, 594 * mm),
  6322. 'A3': (297 * mm, 420 * mm),
  6323. 'A4': (210 * mm, 297 * mm),
  6324. 'A5': (148 * mm, 210 * mm),
  6325. 'A6': (105 * mm, 148 * mm),
  6326. 'A7': (74 * mm, 105 * mm),
  6327. 'A8': (52 * mm, 74 * mm),
  6328. 'A9': (37 * mm, 52 * mm),
  6329. 'A10': (26 * mm, 37 * mm),
  6330. 'B0': (1000 * mm, 1414 * mm),
  6331. 'B1': (707 * mm, 1000 * mm),
  6332. 'B2': (500 * mm, 707 * mm),
  6333. 'B3': (353 * mm, 500 * mm),
  6334. 'B4': (250 * mm, 353 * mm),
  6335. 'B5': (176 * mm, 250 * mm),
  6336. 'B6': (125 * mm, 176 * mm),
  6337. 'B7': (88 * mm, 125 * mm),
  6338. 'B8': (62 * mm, 88 * mm),
  6339. 'B9': (44 * mm, 62 * mm),
  6340. 'B10': (31 * mm, 44 * mm),
  6341. 'C0': (917 * mm, 1297 * mm),
  6342. 'C1': (648 * mm, 917 * mm),
  6343. 'C2': (458 * mm, 648 * mm),
  6344. 'C3': (324 * mm, 458 * mm),
  6345. 'C4': (229 * mm, 324 * mm),
  6346. 'C5': (162 * mm, 229 * mm),
  6347. 'C6': (114 * mm, 162 * mm),
  6348. 'C7': (81 * mm, 114 * mm),
  6349. 'C8': (57 * mm, 81 * mm),
  6350. 'C9': (40 * mm, 57 * mm),
  6351. 'C10': (28 * mm, 40 * mm),
  6352. # American paper sizes
  6353. 'LETTER': (8.5 * inch, 11 * inch),
  6354. 'LEGAL': (8.5 * inch, 14 * inch),
  6355. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6356. # From https://en.wikipedia.org/wiki/Paper_size
  6357. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6358. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6359. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6360. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6361. 'LEDGER': (17 * inch, 11 * inch),
  6362. }
  6363. )
  6364. exported_svg = []
  6365. for obj in obj_selection:
  6366. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6367. scale_factor_x=None, scale_factor_y=None,
  6368. skew_factor_x=None, skew_factor_y=None,
  6369. mirror=None)
  6370. if obj.kind.lower() == 'gerber':
  6371. # color = self.defaults["gerber_plot_fill"][:-2]
  6372. color = obj.fill_color[:-2]
  6373. elif obj.kind.lower() == 'excellon':
  6374. color = '#C40000'
  6375. elif obj.kind.lower() == 'geometry':
  6376. color = self.defaults["global_draw_color"]
  6377. # Change the attributes of the exported SVG
  6378. # We don't need stroke-width
  6379. # We set opacity to maximum
  6380. # We set the colour to WHITE
  6381. root = ET.fromstring(svg_obj)
  6382. for child in root:
  6383. child.set('fill', str(color))
  6384. child.set('opacity', str(transparency_level))
  6385. child.set('stroke', str(color))
  6386. exported_svg.append(ET.tostring(root))
  6387. xmin = Inf
  6388. ymin = Inf
  6389. xmax = -Inf
  6390. ymax = -Inf
  6391. for obj in obj_selection:
  6392. try:
  6393. gxmin, gymin, gxmax, gymax = obj.bounds()
  6394. xmin = min([xmin, gxmin])
  6395. ymin = min([ymin, gymin])
  6396. xmax = max([xmax, gxmax])
  6397. ymax = max([ymax, gymax])
  6398. except Exception as e:
  6399. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6400. # Determine bounding area for svg export
  6401. bounds = [xmin, ymin, xmax, ymax]
  6402. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6403. # This contain the measure units
  6404. uom = obj_selection[0].units.lower()
  6405. # Define a boundary around SVG of about 1.0mm (~39mils)
  6406. if uom in "mm":
  6407. boundary = 1.0
  6408. else:
  6409. boundary = 0.0393701
  6410. # Convert everything to strings for use in the xml doc
  6411. svgwidth = str(size[0] + (2 * boundary))
  6412. svgheight = str(size[1] + (2 * boundary))
  6413. minx = str(bounds[0] - boundary)
  6414. miny = str(bounds[1] + boundary + size[1])
  6415. # Add a SVG Header and footer to the svg output from shapely
  6416. # The transform flips the Y Axis so that everything renders
  6417. # properly within svg apps such as inkscape
  6418. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6419. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6420. svg_header += 'width="' + svgwidth + uom + '" '
  6421. svg_header += 'height="' + svgheight + uom + '" '
  6422. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6423. svg_header += '>'
  6424. svg_header += '<g transform="scale(1,-1)">'
  6425. svg_footer = '</g> </svg>'
  6426. svg_elem = str(svg_header)
  6427. for svg_item in exported_svg:
  6428. svg_elem += str(svg_item)
  6429. svg_elem += str(svg_footer)
  6430. # Parse the xml through a xml parser just to add line feeds
  6431. # and to make it look more pretty for the output
  6432. doc = parse_xml_string(svg_elem)
  6433. doc_final = doc.toprettyxml()
  6434. try:
  6435. if self.defaults['units'].upper() == 'IN':
  6436. unit = inch
  6437. else:
  6438. unit = mm
  6439. doc_final = StringIO(doc_final)
  6440. drawing = svg2rlg(doc_final)
  6441. if p_size == 'Bounds':
  6442. renderPDF.drawToFile(drawing, file_name)
  6443. else:
  6444. if orientation == 'p':
  6445. page_size = portrait(self.pagesize[p_size])
  6446. else:
  6447. page_size = landscape(self.pagesize[p_size])
  6448. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6449. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6450. renderPDF.draw(drawing, my_canvas, 0, 0)
  6451. my_canvas.save()
  6452. except Exception as e:
  6453. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6454. return 'fail'
  6455. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6456. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6457. """
  6458. Exports a Geometry Object to an SVG file.
  6459. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6460. :param filename: Path to the SVG file to save to.
  6461. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6462. :return:
  6463. """
  6464. self.defaults.report_usage("export_svg()")
  6465. if filename is None:
  6466. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6467. is not None else self.defaults["global_last_folder"]
  6468. self.log.debug("export_svg()")
  6469. try:
  6470. obj = self.collection.get_by_name(str(obj_name))
  6471. except Exception:
  6472. # TODO: The return behavior has not been established... should raise exception?
  6473. return "Could not retrieve object: %s" % obj_name
  6474. with self.proc_container.new(_("Exporting SVG")) as proc:
  6475. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6476. # Determine bounding area for svg export
  6477. bounds = obj.bounds()
  6478. size = obj.size()
  6479. # Convert everything to strings for use in the xml doc
  6480. svgwidth = str(size[0])
  6481. svgheight = str(size[1])
  6482. minx = str(bounds[0])
  6483. miny = str(bounds[1] - size[1])
  6484. uom = obj.units.lower()
  6485. # Add a SVG Header and footer to the svg output from shapely
  6486. # The transform flips the Y Axis so that everything renders
  6487. # properly within svg apps such as inkscape
  6488. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6489. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6490. svg_header += 'width="' + svgwidth + uom + '" '
  6491. svg_header += 'height="' + svgheight + uom + '" '
  6492. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6493. svg_header += '<g transform="scale(1,-1)">'
  6494. svg_footer = '</g> </svg>'
  6495. svg_elem = svg_header + exported_svg + svg_footer
  6496. # Parse the xml through a xml parser just to add line feeds
  6497. # and to make it look more pretty for the output
  6498. svgcode = parse_xml_string(svg_elem)
  6499. svgcode = svgcode.toprettyxml()
  6500. try:
  6501. with open(filename, 'w') as fp:
  6502. fp.write(svgcode)
  6503. except PermissionError:
  6504. self.inform.emit('[WARNING] %s' %
  6505. _("Permission denied, saving not possible.\n"
  6506. "Most likely another app is holding the file open and not accessible."))
  6507. return 'fail'
  6508. if self.defaults["global_open_style"] is False:
  6509. self.file_opened.emit("SVG", filename)
  6510. self.file_saved.emit("SVG", filename)
  6511. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6512. def save_source_file(self, obj_name, filename, use_thread=True):
  6513. """
  6514. Exports a FlatCAM Object to an Gerber/Excellon file.
  6515. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6516. :param filename: Path to the Gerber file to save to.
  6517. :param use_thread: if to be run in a separate thread
  6518. :return:
  6519. """
  6520. self.defaults.report_usage("save source file()")
  6521. if filename is None:
  6522. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6523. is not None else self.defaults["global_last_folder"]
  6524. self.log.debug("save source file()")
  6525. obj = self.collection.get_by_name(obj_name)
  6526. file_string = StringIO(obj.source_file)
  6527. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6528. if file_string.getvalue() == '':
  6529. self.inform.emit('[ERROR_NOTCL] %s' %
  6530. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6531. return 'fail'
  6532. try:
  6533. with open(filename, 'w') as file:
  6534. file.writelines('G04*\n')
  6535. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6536. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6537. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6538. file.writelines('G04 Created on : %s*\n' % time_string)
  6539. for line in file_string:
  6540. file.writelines(line)
  6541. except PermissionError:
  6542. self.inform.emit('[WARNING] %s' %
  6543. _("Permission denied, saving not possible.\n"
  6544. "Most likely another app is holding the file open and not accessible."))
  6545. return 'fail'
  6546. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6547. """
  6548. Exports a Excellon Object to an Excellon file.
  6549. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6550. :param filename: Path to the Excellon file to save to.
  6551. :param local_use:
  6552. :param use_thread: if to be run in a separate thread
  6553. :return:
  6554. """
  6555. self.defaults.report_usage("export_excellon()")
  6556. if filename is None:
  6557. if self.defaults["global_last_save_folder"]:
  6558. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6559. else:
  6560. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6561. self.log.debug("export_excellon()")
  6562. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6563. self.defaults["excellon_exp_decimals"]
  6564. )
  6565. if local_use is None:
  6566. try:
  6567. obj = self.collection.get_by_name(str(obj_name))
  6568. except Exception:
  6569. return "Could not retrieve object: %s" % obj_name
  6570. else:
  6571. obj = local_use
  6572. if not isinstance(obj, ExcellonObject):
  6573. self.inform.emit('[ERROR_NOTCL] %s' %
  6574. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6575. return
  6576. # updated units
  6577. eunits = self.defaults["excellon_exp_units"]
  6578. ewhole = self.defaults["excellon_exp_integer"]
  6579. efract = self.defaults["excellon_exp_decimals"]
  6580. ezeros = self.defaults["excellon_exp_zeros"]
  6581. eformat = self.defaults["excellon_exp_format"]
  6582. slot_type = self.defaults["excellon_exp_slot_type"]
  6583. fc_units = self.defaults['units'].upper()
  6584. if fc_units == 'MM':
  6585. factor = 1 if eunits == 'METRIC' else 0.03937
  6586. else:
  6587. factor = 25.4 if eunits == 'METRIC' else 1
  6588. def make_excellon():
  6589. try:
  6590. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6591. header = 'M48\n'
  6592. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6593. (str(self.version), str(self.version_date))
  6594. header += ';Filename: %s' % str(obj_name) + '\n'
  6595. header += ';Created on : %s' % time_str + '\n'
  6596. if eformat == 'dec':
  6597. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6598. header += eunits + '\n'
  6599. for tool in obj.tools:
  6600. if eunits == 'METRIC':
  6601. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6602. tool=str(tool),
  6603. dec=2)
  6604. else:
  6605. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6606. tool=str(tool),
  6607. dec=4)
  6608. else:
  6609. if ezeros == 'LZ':
  6610. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6611. form='ndec', e_zeros='LZ', factor=factor,
  6612. slot_type=slot_type)
  6613. header += '%s,%s\n' % (eunits, 'LZ')
  6614. header += format_exc
  6615. for tool in obj.tools:
  6616. if eunits == 'METRIC':
  6617. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6618. tool=str(tool),
  6619. dec=2)
  6620. else:
  6621. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6622. tool=str(tool),
  6623. dec=4)
  6624. else:
  6625. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6626. form='ndec', e_zeros='TZ', factor=factor,
  6627. slot_type=slot_type)
  6628. header += '%s,%s\n' % (eunits, 'TZ')
  6629. header += format_exc
  6630. for tool in obj.tools:
  6631. if eunits == 'METRIC':
  6632. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6633. tool=str(tool),
  6634. dec=2)
  6635. else:
  6636. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6637. tool=str(tool),
  6638. dec=4)
  6639. header += '%\n'
  6640. footer = 'M30\n'
  6641. exported_excellon = header
  6642. exported_excellon += excellon_code
  6643. exported_excellon += footer
  6644. if local_use is None:
  6645. try:
  6646. with open(filename, 'w') as fp:
  6647. fp.write(exported_excellon)
  6648. except PermissionError:
  6649. self.inform.emit('[WARNING] %s' %
  6650. _("Permission denied, saving not possible.\n"
  6651. "Most likely another app is holding the file open and not accessible."))
  6652. return 'fail'
  6653. if self.defaults["global_open_style"] is False:
  6654. self.file_opened.emit("Excellon", filename)
  6655. self.file_saved.emit("Excellon", filename)
  6656. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6657. else:
  6658. return exported_excellon
  6659. except Exception as e:
  6660. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6661. return 'fail'
  6662. if use_thread is True:
  6663. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6664. def job_thread_exc(app_obj):
  6665. ret = make_excellon()
  6666. if ret == 'fail':
  6667. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6668. return
  6669. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6670. else:
  6671. eret = make_excellon()
  6672. if eret == 'fail':
  6673. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6674. return 'fail'
  6675. if local_use is not None:
  6676. return eret
  6677. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6678. """
  6679. Exports a Gerber Object to an Gerber file.
  6680. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6681. :param filename: Path to the Gerber file to save to.
  6682. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6683. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6684. :param use_thread: if to be run in a separate thread
  6685. :return:
  6686. """
  6687. self.defaults.report_usage("export_gerber()")
  6688. if filename is None:
  6689. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6690. is not None else self.defaults["global_last_folder"]
  6691. self.log.debug("export_gerber()")
  6692. if local_use is None:
  6693. try:
  6694. obj = self.collection.get_by_name(str(obj_name))
  6695. except Exception:
  6696. return "Could not retrieve object: %s" % obj_name
  6697. else:
  6698. obj = local_use
  6699. # updated units
  6700. gunits = self.defaults["gerber_exp_units"]
  6701. gwhole = self.defaults["gerber_exp_integer"]
  6702. gfract = self.defaults["gerber_exp_decimals"]
  6703. gzeros = self.defaults["gerber_exp_zeros"]
  6704. fc_units = self.defaults['units'].upper()
  6705. if fc_units == 'MM':
  6706. factor = 1 if gunits == 'MM' else 0.03937
  6707. else:
  6708. factor = 25.4 if gunits == 'MM' else 1
  6709. def make_gerber():
  6710. try:
  6711. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6712. header = 'G04*\n'
  6713. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6714. (str(self.version), str(self.version_date))
  6715. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6716. header += 'G04 Created on : %s*' % time_str + '\n'
  6717. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6718. header += "%MO{units}*%\n".format(units=gunits)
  6719. for apid in obj.apertures:
  6720. if obj.apertures[apid]['type'] == 'C':
  6721. header += "%ADD{apid}{type},{size}*%\n".format(
  6722. apid=str(apid),
  6723. type='C',
  6724. size=(factor * obj.apertures[apid]['size'])
  6725. )
  6726. elif obj.apertures[apid]['type'] == 'R':
  6727. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6728. apid=str(apid),
  6729. type='R',
  6730. width=(factor * obj.apertures[apid]['width']),
  6731. height=(factor * obj.apertures[apid]['height'])
  6732. )
  6733. elif obj.apertures[apid]['type'] == 'O':
  6734. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6735. apid=str(apid),
  6736. type='O',
  6737. width=(factor * obj.apertures[apid]['width']),
  6738. height=(factor * obj.apertures[apid]['height'])
  6739. )
  6740. header += '\n'
  6741. # obsolete units but some software may need it
  6742. if gunits == 'IN':
  6743. header += 'G70*\n'
  6744. else:
  6745. header += 'G71*\n'
  6746. # Absolute Mode
  6747. header += 'G90*\n'
  6748. header += 'G01*\n'
  6749. # positive polarity
  6750. header += '%LPD*%\n'
  6751. footer = 'M02*\n'
  6752. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6753. exported_gerber = header
  6754. exported_gerber += gerber_code
  6755. exported_gerber += footer
  6756. if local_use is None:
  6757. try:
  6758. with open(filename, 'w') as fp:
  6759. fp.write(exported_gerber)
  6760. except PermissionError:
  6761. self.inform.emit('[WARNING] %s' %
  6762. _("Permission denied, saving not possible.\n"
  6763. "Most likely another app is holding the file open and not accessible."))
  6764. return 'fail'
  6765. if self.defaults["global_open_style"] is False:
  6766. self.file_opened.emit("Gerber", filename)
  6767. self.file_saved.emit("Gerber", filename)
  6768. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6769. else:
  6770. return exported_gerber
  6771. except Exception as e:
  6772. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6773. return 'fail'
  6774. if use_thread is True:
  6775. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6776. def job_thread_grb(app_obj):
  6777. ret = make_gerber()
  6778. if ret == 'fail':
  6779. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6780. return
  6781. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6782. else:
  6783. gret = make_gerber()
  6784. if gret == 'fail':
  6785. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6786. return 'fail'
  6787. if local_use is not None:
  6788. return gret
  6789. def export_dxf(self, obj_name, filename, use_thread=True):
  6790. """
  6791. Exports a Geometry Object to an DXF file.
  6792. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6793. :param filename: Path to the DXF file to save to.
  6794. :param use_thread: if to be run in a separate thread
  6795. :return:
  6796. """
  6797. self.defaults.report_usage("export_dxf()")
  6798. if filename is None:
  6799. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6800. is not None else self.defaults["global_last_folder"]
  6801. self.log.debug("export_dxf()")
  6802. try:
  6803. obj = self.collection.get_by_name(str(obj_name))
  6804. except Exception:
  6805. # TODO: The return behavior has not been established... should raise exception?
  6806. return "Could not retrieve object: %s" % obj_name
  6807. def make_dxf():
  6808. try:
  6809. dxf_code = obj.export_dxf()
  6810. dxf_code.saveas(filename)
  6811. if self.defaults["global_open_style"] is False:
  6812. self.file_opened.emit("DXF", filename)
  6813. self.file_saved.emit("DXF", filename)
  6814. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6815. except Exception:
  6816. return 'fail'
  6817. if use_thread is True:
  6818. with self.proc_container.new(_("Exporting DXF")) as proc:
  6819. def job_thread_exc(app_obj):
  6820. ret_dxf_val = make_dxf()
  6821. if ret_dxf_val == 'fail':
  6822. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6823. return
  6824. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6825. else:
  6826. ret = make_dxf()
  6827. if ret == 'fail':
  6828. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6829. return
  6830. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6831. """
  6832. Adds a new Geometry Object to the projects and populates
  6833. it with shapes extracted from the SVG file.
  6834. :param plot: If True then the resulting object will be plotted on canvas
  6835. :param filename: Path to the SVG file.
  6836. :param geo_type: Type of FlatCAM object that will be created from SVG
  6837. :param outname: The name given to the resulting FlatCAM object
  6838. :return:
  6839. """
  6840. self.defaults.report_usage("import_svg()")
  6841. log.debug("App.import_svg()")
  6842. obj_type = ""
  6843. if geo_type is None or geo_type == "geometry":
  6844. obj_type = "geometry"
  6845. elif geo_type == "gerber":
  6846. obj_type = "gerber"
  6847. else:
  6848. self.inform.emit('[ERROR_NOTCL] %s' %
  6849. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6850. return
  6851. units = self.defaults['units'].upper()
  6852. def obj_init(geo_obj, app_obj):
  6853. geo_obj.import_svg(filename, obj_type, units=units)
  6854. geo_obj.multigeo = False
  6855. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6856. with self.proc_container.new(_("Importing SVG")) as proc:
  6857. # Object name
  6858. name = outname or filename.split('/')[-1].split('\\')[-1]
  6859. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6860. if ret == 'fail':
  6861. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6862. return 'fail'
  6863. # Register recent file
  6864. self.file_opened.emit("svg", filename)
  6865. # AppGUI feedback
  6866. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6867. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  6868. """
  6869. Adds a new Geometry Object to the projects and populates
  6870. it with shapes extracted from the DXF file.
  6871. :param filename: Path to the DXF file.
  6872. :param geo_type: Type of FlatCAM object that will be created from DXF
  6873. :param outname: Name for the imported Geometry
  6874. :param plot: If True then the resulting object will be plotted on canvas
  6875. :return:
  6876. """
  6877. self.defaults.report_usage("import_dxf()")
  6878. obj_type = ""
  6879. if geo_type is None or geo_type == "geometry":
  6880. obj_type = "geometry"
  6881. elif geo_type == "gerber":
  6882. obj_type = geo_type
  6883. else:
  6884. self.inform.emit('[ERROR_NOTCL] %s' %
  6885. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6886. return
  6887. units = self.defaults['units'].upper()
  6888. def obj_init(geo_obj, app_obj):
  6889. geo_obj.import_dxf(filename, obj_type, units=units)
  6890. geo_obj.multigeo = False
  6891. with self.proc_container.new(_("Importing DXF")):
  6892. # Object name
  6893. name = outname or filename.split('/')[-1].split('\\')[-1]
  6894. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6895. if ret == 'fail':
  6896. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  6897. return 'fail'
  6898. # Register recent file
  6899. self.file_opened.emit("dxf", filename)
  6900. # AppGUI feedback
  6901. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6902. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  6903. """
  6904. Opens a Gerber file, parses it and creates a new object for
  6905. it in the program. Thread-safe.
  6906. :param outname: Name of the resulting object. None causes the
  6907. name to be that of the file. Str.
  6908. :param filename: Gerber file filename
  6909. :type filename: str
  6910. :param plot: boolean, to plot or not the resulting object
  6911. :param from_tcl: True if run from Tcl Shell
  6912. :return: None
  6913. """
  6914. # How the object should be initialized
  6915. def obj_init(gerber_obj, app_obj):
  6916. assert isinstance(gerber_obj, GerberObject), \
  6917. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  6918. # Opening the file happens here
  6919. try:
  6920. gerber_obj.parse_file(filename)
  6921. except IOError:
  6922. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  6923. return "fail"
  6924. except ParseError as err:
  6925. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  6926. app_obj.log.error(str(err))
  6927. return "fail"
  6928. except Exception as e:
  6929. log.debug("App.open_gerber() --> %s" % str(e))
  6930. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  6931. msg += traceback.format_exc()
  6932. app_obj.inform.emit(msg)
  6933. return "fail"
  6934. if gerber_obj.is_empty():
  6935. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  6936. _("Object is not Gerber file or empty. Aborting object creation."))
  6937. return "fail"
  6938. App.log.debug("open_gerber()")
  6939. with self.proc_container.new(_("Opening Gerber")):
  6940. # Object name
  6941. name = outname or filename.split('/')[-1].split('\\')[-1]
  6942. # # ## Object creation # ##
  6943. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6944. if ret_val == 'fail':
  6945. if from_tcl:
  6946. filename = self.defaults['global_tcl_path'] + '/' + name
  6947. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  6948. if ret_val == 'fail':
  6949. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  6950. return 'fail'
  6951. # Register recent file
  6952. self.file_opened.emit("gerber", filename)
  6953. # AppGUI feedback
  6954. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  6955. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  6956. """
  6957. Opens an Excellon file, parses it and creates a new object for
  6958. it in the program. Thread-safe.
  6959. :param outname: Name of the resulting object. None causes the name to be that of the file.
  6960. :param filename: Excellon file filename
  6961. :type filename: str
  6962. :param plot: boolean, to plot or not the resulting object
  6963. :param from_tcl: True if run from Tcl Shell
  6964. :return: None
  6965. """
  6966. App.log.debug("open_excellon()")
  6967. # How the object should be initialized
  6968. def obj_init(excellon_obj, app_obj):
  6969. try:
  6970. ret = excellon_obj.parse_file(filename=filename)
  6971. if ret == "fail":
  6972. log.debug("Excellon parsing failed.")
  6973. self.inform.emit('[ERROR_NOTCL] %s' %
  6974. _("This is not Excellon file."))
  6975. return "fail"
  6976. except IOError:
  6977. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  6978. (_("Cannot open file"), filename))
  6979. log.debug("Could not open Excellon object.")
  6980. return "fail"
  6981. except Exception:
  6982. msg = '[ERROR_NOTCL] %s' % \
  6983. _("An internal error has occurred. See shell.\n")
  6984. msg += traceback.format_exc()
  6985. app_obj.inform.emit(msg)
  6986. return "fail"
  6987. ret = excellon_obj.create_geometry()
  6988. if ret == 'fail':
  6989. log.debug("Could not create geometry for Excellon object.")
  6990. return "fail"
  6991. for tool in excellon_obj.tools:
  6992. if excellon_obj.tools[tool]['solid_geometry']:
  6993. return
  6994. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  6995. return "fail"
  6996. with self.proc_container.new(_("Opening Excellon.")):
  6997. # Object name
  6998. name = outname or filename.split('/')[-1].split('\\')[-1]
  6999. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7000. if ret_val == 'fail':
  7001. if from_tcl:
  7002. filename = self.defaults['global_tcl_path'] + '/' + name
  7003. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7004. if ret_val == 'fail':
  7005. self.inform.emit('[ERROR_NOTCL] %s' %
  7006. _('Open Excellon file failed. Probable not an Excellon file.'))
  7007. return
  7008. # Register recent file
  7009. self.file_opened.emit("excellon", filename)
  7010. # AppGUI feedback
  7011. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7012. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7013. """
  7014. Opens a G-gcode file, parses it and creates a new object for
  7015. it in the program. Thread-safe.
  7016. :param filename: G-code file filename
  7017. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7018. :param force_parsing:
  7019. :param plot: If True plot the object on canvas
  7020. :param from_tcl: True if run from Tcl Shell
  7021. :return: None
  7022. """
  7023. App.log.debug("open_gcode()")
  7024. # How the object should be initialized
  7025. def obj_init(job_obj, app_obj_):
  7026. """
  7027. :param job_obj: the resulting object
  7028. :type app_obj_: App
  7029. """
  7030. assert isinstance(app_obj_, App), \
  7031. "Initializer expected App, got %s" % type(app_obj_)
  7032. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7033. try:
  7034. f = open(filename)
  7035. gcode = f.read()
  7036. f.close()
  7037. except IOError:
  7038. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7039. return "fail"
  7040. job_obj.gcode = gcode
  7041. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7042. if gcode_ret == "fail":
  7043. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7044. return "fail"
  7045. job_obj.create_geometry()
  7046. with self.proc_container.new(_("Opening G-Code.")):
  7047. # Object name
  7048. name = outname or filename.split('/')[-1].split('\\')[-1]
  7049. # New object creation and file processing
  7050. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7051. if ret_val == 'fail':
  7052. if from_tcl:
  7053. filename = self.defaults['global_tcl_path'] + '/' + name
  7054. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7055. if ret_val == 'fail':
  7056. self.inform.emit('[ERROR_NOTCL] %s' %
  7057. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7058. "Try to load it from File menu.\n "
  7059. "Attempting to create a FlatCAM CNCJob Object from "
  7060. "G-Code file failed during processing"))
  7061. return "fail"
  7062. # Register recent file
  7063. self.file_opened.emit("cncjob", filename)
  7064. # AppGUI feedback
  7065. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7066. def open_hpgl2(self, filename, outname=None):
  7067. """
  7068. Opens a HPGL2 file, parses it and creates a new object for
  7069. it in the program. Thread-safe.
  7070. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7071. :param filename: HPGL2 file filename
  7072. :return: None
  7073. """
  7074. filename = filename
  7075. # How the object should be initialized
  7076. def obj_init(geo_obj, app_obj):
  7077. assert isinstance(geo_obj, GeometryObject), \
  7078. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7079. # Opening the file happens here
  7080. obj = HPGL2(self)
  7081. try:
  7082. HPGL2.parse_file(obj, filename)
  7083. except IOError:
  7084. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7085. return "fail"
  7086. except ParseError as err:
  7087. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7088. app_obj.log.error(str(err))
  7089. return "fail"
  7090. except Exception as e:
  7091. log.debug("App.open_hpgl2() --> %s" % str(e))
  7092. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7093. msg += traceback.format_exc()
  7094. app_obj.inform.emit(msg)
  7095. return "fail"
  7096. geo_obj.multigeo = True
  7097. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7098. geo_obj.tools = deepcopy(obj.tools)
  7099. geo_obj.source_file = deepcopy(obj.source_file)
  7100. del obj
  7101. if not geo_obj.solid_geometry:
  7102. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7103. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7104. return "fail"
  7105. App.log.debug("open_hpgl2()")
  7106. with self.proc_container.new(_("Opening HPGL2")):
  7107. # Object name
  7108. name = outname or filename.split('/')[-1].split('\\')[-1]
  7109. # # ## Object creation # ##
  7110. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7111. if ret == 'fail':
  7112. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7113. return 'fail'
  7114. # Register recent file
  7115. self.file_opened.emit("geometry", filename)
  7116. # AppGUI feedback
  7117. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7118. def open_script(self, filename, outname=None, silent=False):
  7119. """
  7120. Opens a Script file, parses it and creates a new object for
  7121. it in the program. Thread-safe.
  7122. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7123. :param filename: Script file filename
  7124. :param silent: If True there will be no messages printed to StatusBar
  7125. :return: None
  7126. """
  7127. def obj_init(script_obj, app_obj):
  7128. assert isinstance(script_obj, ScriptObject), \
  7129. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7130. if silent is False:
  7131. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7132. try:
  7133. script_obj.parse_file(filename)
  7134. except IOError:
  7135. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7136. return "fail"
  7137. except ParseError as err:
  7138. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7139. app_obj.log.error(str(err))
  7140. return "fail"
  7141. except Exception as e:
  7142. log.debug("App.open_script() -> %s" % str(e))
  7143. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7144. msg += traceback.format_exc()
  7145. app_obj.inform.emit(msg)
  7146. return "fail"
  7147. App.log.debug("open_script()")
  7148. with self.proc_container.new(_("Opening TCL Script...")):
  7149. # Object name
  7150. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7151. # Object creation
  7152. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7153. if ret_val == 'fail':
  7154. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7155. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7156. if ret_val == 'fail':
  7157. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7158. return 'fail'
  7159. # Register recent file
  7160. self.file_opened.emit("script", filename)
  7161. # AppGUI feedback
  7162. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7163. def open_config_file(self, filename, run_from_arg=None):
  7164. """
  7165. Loads a config file from the specified file.
  7166. :param filename: Name of the file from which to load.
  7167. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7168. :return: None
  7169. """
  7170. App.log.debug("Opening config file: " + filename)
  7171. if run_from_arg:
  7172. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7173. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7174. _("Opening FlatCAM Config file.")),
  7175. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7176. color=QtGui.QColor("gray"))
  7177. # # add the tab if it was closed
  7178. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7179. # # first clear previous text in text editor (if any)
  7180. # self.ui.text_editor_tab.code_editor.clear()
  7181. #
  7182. # # Switch plot_area to CNCJob tab
  7183. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7184. # close the Code editor if already open
  7185. if self.toggle_codeeditor:
  7186. self.on_toggle_code_editor()
  7187. self.on_toggle_code_editor()
  7188. try:
  7189. if filename:
  7190. f = QtCore.QFile(filename)
  7191. if f.open(QtCore.QIODevice.ReadOnly):
  7192. stream = QtCore.QTextStream(f)
  7193. code_edited = stream.readAll()
  7194. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7195. f.close()
  7196. except IOError:
  7197. App.log.error("Failed to open config file: %s" % filename)
  7198. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7199. (_("Failed to open config file"), filename))
  7200. return
  7201. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7202. """
  7203. Loads a project from the specified file.
  7204. 1) Loads and parses file
  7205. 2) Registers the file as recently opened.
  7206. 3) Calls on_file_new()
  7207. 4) Updates options
  7208. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7209. 6) Calls plot_all() if plot=True
  7210. :param filename: Name of the file from which to load.
  7211. :param run_from_arg: True if run for arguments
  7212. :param plot: If True plot all objects in the project
  7213. :param cli: Run from command line
  7214. :param from_tcl: True if run from Tcl Sehll
  7215. :return: None
  7216. """
  7217. App.log.debug("Opening project: " + filename)
  7218. # block autosaving while a project is loaded
  7219. self.block_autosave = True
  7220. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7221. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7222. if cli is None:
  7223. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7224. if run_from_arg:
  7225. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7226. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7227. _("Opening FlatCAM Project file.")),
  7228. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7229. color=QtGui.QColor("gray"))
  7230. # Open and parse an uncompressed Project file
  7231. try:
  7232. f = open(filename, 'r')
  7233. except IOError:
  7234. if from_tcl:
  7235. name = filename.split('/')[-1].split('\\')[-1]
  7236. filename = self.defaults['global_tcl_path'] + '/' + name
  7237. try:
  7238. f = open(filename, 'r')
  7239. except IOError:
  7240. log.error("Failed to open project file: %s" % filename)
  7241. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7242. return
  7243. else:
  7244. log.error("Failed to open project file: %s" % filename)
  7245. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7246. return
  7247. try:
  7248. d = json.load(f, object_hook=dict2obj)
  7249. except Exception as e:
  7250. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7251. (filename, str(e)))
  7252. f.close()
  7253. # Open and parse a compressed Project file
  7254. try:
  7255. with lzma.open(filename) as f:
  7256. file_content = f.read().decode('utf-8')
  7257. d = json.loads(file_content, object_hook=dict2obj)
  7258. except Exception as e:
  7259. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7260. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7261. return
  7262. # Clear the current project
  7263. # # NOT THREAD SAFE # ##
  7264. if run_from_arg is True:
  7265. pass
  7266. elif cli is True:
  7267. self.delete_selection_shape()
  7268. else:
  7269. self.on_file_new()
  7270. # Project options
  7271. self.options.update(d['options'])
  7272. self.project_filename = filename
  7273. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7274. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7275. if cli is None:
  7276. self.set_screen_units(self.options["units"])
  7277. # Re create objects
  7278. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7279. for obj in d['objs']:
  7280. try:
  7281. def obj_init(obj_inst, app_inst):
  7282. obj_inst.from_dict(obj)
  7283. App.log.debug("Recreating from opened project an %s object: %s" %
  7284. (obj['kind'].capitalize(), obj['options']['name']))
  7285. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7286. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7287. if cli is None:
  7288. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7289. obj['kind'].upper(),
  7290. obj['options']['name']
  7291. )
  7292. )
  7293. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7294. except Exception as e:
  7295. print('App.open_project() --> ' + str(e))
  7296. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7297. self.should_we_save = False
  7298. self.file_opened.emit("project", filename)
  7299. # restore autosaving after a project was loaded
  7300. self.block_autosave = False
  7301. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7302. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7303. if cli is None:
  7304. self.set_ui_title(name=self.project_filename)
  7305. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7306. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7307. """
  7308. Re-generates all plots from all objects.
  7309. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7310. :param muted: if True don't print messages
  7311. :param use_thread: if True will use threading for plotting the objects
  7312. :return: None
  7313. """
  7314. self.log.debug("Plot_all()")
  7315. if muted is not True:
  7316. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  7317. for plot_obj in self.collection.get_list():
  7318. def worker_task(obj):
  7319. with self.proc_container.new("Plotting"):
  7320. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7321. if fit_view is True:
  7322. self.app_obj.object_plotted.emit(obj)
  7323. if use_thread is True:
  7324. # Send to worker
  7325. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7326. else:
  7327. worker_task(plot_obj)
  7328. def register_folder(self, filename):
  7329. """
  7330. Register the last folder used by the app to open something
  7331. :param filename: the last folder is extracted from the filename
  7332. :return: None
  7333. """
  7334. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7335. def register_save_folder(self, filename):
  7336. """
  7337. Register the last folder used by the app to save something
  7338. :param filename: the last folder is extracted from the filename
  7339. :return: None
  7340. """
  7341. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7342. # def set_progress_bar(self, percentage, text=""):
  7343. # """
  7344. # Set a progress bar to a value (percentage)
  7345. #
  7346. # :param percentage: Value set to the progressbar
  7347. # :param text: Not used
  7348. # :return: None
  7349. # """
  7350. # self.ui.progress_bar.setValue(int(percentage))
  7351. def setup_recent_items(self):
  7352. """
  7353. Setup a dictionary with the recent files accessed, organized by type
  7354. :return:
  7355. """
  7356. icons = {
  7357. "gerber": self.resource_location + "/flatcam_icon16.png",
  7358. "excellon": self.resource_location + "/drill16.png",
  7359. 'geometry': self.resource_location + "/geometry16.png",
  7360. "cncjob": self.resource_location + "/cnc16.png",
  7361. "script": self.resource_location + "/script_new24.png",
  7362. "document": self.resource_location + "/notes16_1.png",
  7363. "project": self.resource_location + "/project16.png",
  7364. "svg": self.resource_location + "/geometry16.png",
  7365. "dxf": self.resource_location + "/dxf16.png",
  7366. "pdf": self.resource_location + "/pdf32.png",
  7367. "image": self.resource_location + "/image16.png"
  7368. }
  7369. try:
  7370. image_opener = self.image_tool.import_image
  7371. except AttributeError:
  7372. image_opener = None
  7373. openers = {
  7374. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7375. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7376. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7377. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7378. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7379. "document": None,
  7380. 'project': self.open_project,
  7381. 'svg': self.import_svg,
  7382. 'dxf': self.import_dxf,
  7383. 'image': image_opener,
  7384. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7385. }
  7386. # Open recent file for files
  7387. try:
  7388. f = open(self.data_path + '/recent.json')
  7389. except IOError:
  7390. App.log.error("Failed to load recent item list.")
  7391. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7392. return
  7393. try:
  7394. self.recent = json.load(f)
  7395. except json.errors.JSONDecodeError:
  7396. App.log.error("Failed to parse recent item list.")
  7397. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7398. f.close()
  7399. return
  7400. f.close()
  7401. # Open recent file for projects
  7402. try:
  7403. fp = open(self.data_path + '/recent_projects.json')
  7404. except IOError:
  7405. App.log.error("Failed to load recent project item list.")
  7406. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7407. return
  7408. try:
  7409. self.recent_projects = json.load(fp)
  7410. except json.errors.JSONDecodeError:
  7411. App.log.error("Failed to parse recent project item list.")
  7412. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7413. fp.close()
  7414. return
  7415. fp.close()
  7416. # Closure needed to create callbacks in a loop.
  7417. # Otherwise late binding occurs.
  7418. def make_callback(func, fname):
  7419. def opener():
  7420. func(fname)
  7421. return opener
  7422. def reset_recent_files():
  7423. # Reset menu
  7424. self.ui.recent.clear()
  7425. self.recent = []
  7426. try:
  7427. ff = open(self.data_path + '/recent.json', 'w')
  7428. except IOError:
  7429. App.log.error("Failed to open recent items file for writing.")
  7430. return
  7431. json.dump(self.recent, ff)
  7432. def reset_recent_projects():
  7433. # Reset menu
  7434. self.ui.recent_projects.clear()
  7435. self.recent_projects = []
  7436. try:
  7437. frp = open(self.data_path + '/recent_projects.json', 'w')
  7438. except IOError:
  7439. App.log.error("Failed to open recent projects items file for writing.")
  7440. return
  7441. json.dump(self.recent, frp)
  7442. # Reset menu
  7443. self.ui.recent.clear()
  7444. self.ui.recent_projects.clear()
  7445. # Create menu items for projects
  7446. for recent in self.recent_projects:
  7447. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7448. if recent['kind'] == 'project':
  7449. try:
  7450. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7451. # Attach callback
  7452. o = make_callback(openers[recent["kind"]], recent['filename'])
  7453. action.triggered.connect(o)
  7454. self.ui.recent_projects.addAction(action)
  7455. except KeyError:
  7456. App.log.error("Unsupported file type: %s" % recent["kind"])
  7457. # Last action in Recent Files menu is one that Clear the content
  7458. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7459. (_("Clear Recent projects")), self)
  7460. clear_action_proj.triggered.connect(reset_recent_projects)
  7461. self.ui.recent_projects.addSeparator()
  7462. self.ui.recent_projects.addAction(clear_action_proj)
  7463. # Create menu items for files
  7464. for recent in self.recent:
  7465. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7466. if recent['kind'] != 'project':
  7467. try:
  7468. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7469. # Attach callback
  7470. o = make_callback(openers[recent["kind"]], recent['filename'])
  7471. action.triggered.connect(o)
  7472. self.ui.recent.addAction(action)
  7473. except KeyError:
  7474. App.log.error("Unsupported file type: %s" % recent["kind"])
  7475. # Last action in Recent Files menu is one that Clear the content
  7476. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7477. (_("Clear Recent files")), self)
  7478. clear_action.triggered.connect(reset_recent_files)
  7479. self.ui.recent.addSeparator()
  7480. self.ui.recent.addAction(clear_action)
  7481. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7482. # self.ui.menufilerecent.set_submenu(recent_menu)
  7483. # recent_menu.show_all()
  7484. # self.ui.recent.show()
  7485. self.log.debug("Recent items list has been populated.")
  7486. def setup_component_editor(self):
  7487. """
  7488. Default text for the Selected tab when is not taken by the Object UI.
  7489. :return:
  7490. """
  7491. # label = QtWidgets.QLabel("Choose an item from Project")
  7492. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7493. sel_title = QtWidgets.QTextEdit(
  7494. _('<b>Shortcut Key List</b>'))
  7495. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7496. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7497. f_settings = QSettings("Open Source", "FlatCAM")
  7498. if f_settings.contains("notebook_font_size"):
  7499. fsize = f_settings.value('notebook_font_size', type=int)
  7500. else:
  7501. fsize = 12
  7502. tsize = fsize + int(fsize / 2)
  7503. # selected_text = (_('''
  7504. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7505. # </p>
  7506. #
  7507. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7508. # The normal flow when working in FlatCAM is the following:</span></p>
  7509. #
  7510. # <ol>
  7511. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7512. # file into
  7513. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7514. # even dragging and dropping the files on the AppGUI.<br />
  7515. # <br />
  7516. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7517. # drop of the
  7518. # file into the FLATCAM AppGUI or through the menu/toolbar links offered within the app.</span><br />
  7519. # &nbsp;</li>
  7520. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7521. # and then
  7522. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7523. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7524. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7525. # <br />
  7526. # If the selection of the object is done on the canvas by single click instead, and the
  7527. # <strong>SELECTED TAB</strong>
  7528. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7529. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7530. # it even if it was out of focus.<br />
  7531. # <br />
  7532. # You can change the parameters in this screen and the flow direction is like this:<br />
  7533. # <br />
  7534. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7535. # <strong> Geometry Object
  7536. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7537. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7538. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7539. # </ol>
  7540. #
  7541. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7542. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7543. # <strong>F3</strong>.</span></p>
  7544. #
  7545. # ''').format(fsize=fsize, tsize=tsize))
  7546. selected_text = '''
  7547. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7548. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7549. {s1}</span></p>
  7550. <ol>
  7551. <li><span style="font-size:{fsize}px">{s2}<br />
  7552. <br />
  7553. {s3}</span><br />
  7554. &nbsp;</li>
  7555. <li><span style="font-size:{fsize}px">{s4}<br />
  7556. &nbsp;</li>
  7557. <br />
  7558. <li><span style="font-size:{fsize}px">{s5}<br />
  7559. &nbsp;</li>
  7560. <br />
  7561. <li><span style="font-size:{fsize}px">{s6}<br />
  7562. <br />
  7563. {s7}</span></li>
  7564. </ol>
  7565. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7566. '''.format(
  7567. title=_("Selected Tab - Choose an Item from Project Tab"),
  7568. subtitle=_("Details"),
  7569. s1=_("The normal flow when working in FlatCAM is the following:"),
  7570. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  7571. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7572. "files on the AppGUI."),
  7573. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  7574. "drag and drop of the file into the FLATCAM AppGUI or through the menu (or toolbar) "
  7575. "actions offered within the app."),
  7576. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7577. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7578. "SELECTED TAB will be updated with the object properties according to its kind: "
  7579. "Gerber, Excellon, Geometry or CNCJob object."),
  7580. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7581. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7582. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7583. "the SELECTED TAB and populate it even if it was out of focus."),
  7584. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7585. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7586. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7587. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7588. "(again, done in SELECTED TAB) --> Save GCode."),
  7589. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7590. "or through its own key shortcut: <b>F3</b>."),
  7591. tsize=tsize,
  7592. fsize=fsize
  7593. )
  7594. sel_title.setText(selected_text)
  7595. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7596. self.ui.selected_scroll_area.setWidget(sel_title)
  7597. def setup_obj_classes(self):
  7598. """
  7599. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7600. class.
  7601. :return: None
  7602. """
  7603. FlatCAMObj.app = self
  7604. ObjectCollection.app = self
  7605. Gerber.app = self
  7606. Excellon.app = self
  7607. Geometry.app = self
  7608. CNCjob.app = self
  7609. FCProcess.app = self
  7610. FCProcessContainer.app = self
  7611. OptionsGroupUI.app = self
  7612. def version_check(self):
  7613. """
  7614. Checks for the latest version of the program. Alerts the
  7615. user if theirs is outdated. This method is meant to be run
  7616. in a separate thread.
  7617. :return: None
  7618. """
  7619. self.log.debug("version_check()")
  7620. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7621. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7622. App.version_url,
  7623. str(self.defaults['global_serial']),
  7624. str(self.version),
  7625. str(self.os),
  7626. urllib.parse.urlencode(self.defaults["global_stats"])
  7627. )
  7628. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7629. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7630. # urllib.parse.urlencode(self.defaults["global_stats"])
  7631. else:
  7632. # no_stats dict; just so it won't break things on website
  7633. no_ststs_dict = {}
  7634. no_ststs_dict["global_ststs"] = {}
  7635. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7636. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7637. App.log.debug("Checking for updates @ %s" % full_url)
  7638. # ## Get the data
  7639. try:
  7640. f = urllib.request.urlopen(full_url)
  7641. except Exception:
  7642. # App.log.warning("Failed checking for latest version. Could not connect.")
  7643. self.log.warning("Failed checking for latest version. Could not connect.")
  7644. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7645. return
  7646. try:
  7647. data = json.load(f)
  7648. except Exception as e:
  7649. App.log.error("Could not parse information about latest version.")
  7650. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7651. App.log.debug("json.load(): %s" % str(e))
  7652. f.close()
  7653. return
  7654. f.close()
  7655. # ## Latest version?
  7656. if self.version >= data["version"]:
  7657. App.log.debug("FlatCAM is up to date!")
  7658. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7659. return
  7660. App.log.debug("Newer version available.")
  7661. self.message.emit(
  7662. _("Newer Version Available"),
  7663. '%s<br><br>><b>%s</b><br>%s' % (
  7664. _("There is a newer version of FlatCAM available for download:"),
  7665. str(data["name"]),
  7666. str(data["message"])
  7667. ),
  7668. _("info")
  7669. )
  7670. def on_plotcanvas_setup(self, container=None):
  7671. """
  7672. This is doing the setup for the plot area (canvas).
  7673. :param container: QT Widget where to install the canvas
  7674. :return: None
  7675. """
  7676. if container:
  7677. plot_container = container
  7678. else:
  7679. plot_container = self.ui.right_layout
  7680. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7681. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7682. self.is_legacy = True
  7683. self.defaults["global_graphic_engine"] = "2D"
  7684. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7685. else:
  7686. try:
  7687. self.plotcanvas = PlotCanvas(plot_container, self)
  7688. except Exception as er:
  7689. msg_txt = traceback.format_exc()
  7690. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7691. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7692. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7693. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7694. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7695. msg += msg_txt
  7696. self.inform.emit(msg)
  7697. return 'fail'
  7698. # So it can receive key presses
  7699. self.plotcanvas.native.setFocus()
  7700. if self.is_legacy is False:
  7701. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7702. # Set the mouse button for panning
  7703. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7704. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7705. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7706. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7707. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7708. # Keys over plot enabled
  7709. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7710. if self.defaults['global_cursor_type'] == 'small':
  7711. self.app_cursor = self.plotcanvas.new_cursor()
  7712. else:
  7713. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7714. if self.ui.grid_snap_btn.isChecked():
  7715. self.app_cursor.enabled = True
  7716. else:
  7717. self.app_cursor.enabled = False
  7718. if self.is_legacy is False:
  7719. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7720. else:
  7721. # will use the default Matplotlib axes
  7722. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7723. def on_zoom_fit(self):
  7724. """
  7725. Callback for zoom-fit request. This can be either from the corresponding
  7726. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7727. with axes limits from the geometry bounds of all objects.
  7728. :return: None
  7729. """
  7730. if self.is_legacy is False:
  7731. self.plotcanvas.fit_view()
  7732. else:
  7733. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7734. width = xmax - xmin
  7735. height = ymax - ymin
  7736. xmin -= 0.05 * width
  7737. xmax += 0.05 * width
  7738. ymin -= 0.05 * height
  7739. ymax += 0.05 * height
  7740. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7741. def on_zoom_in(self):
  7742. """
  7743. Callback for zoom-in request.
  7744. :return:
  7745. """
  7746. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7747. def on_zoom_out(self):
  7748. """
  7749. Callback for zoom-out request.
  7750. :return:
  7751. """
  7752. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7753. def disable_all_plots(self):
  7754. self.defaults.report_usage("disable_all_plots()")
  7755. self.disable_plots(self.collection.get_list())
  7756. self.inform.emit('[success] %s' %
  7757. _("All plots disabled."))
  7758. def disable_other_plots(self):
  7759. self.defaults.report_usage("disable_other_plots()")
  7760. self.disable_plots(self.collection.get_non_selected())
  7761. self.inform.emit('[success] %s' %
  7762. _("All non selected plots disabled."))
  7763. def enable_all_plots(self):
  7764. self.defaults.report_usage("enable_all_plots()")
  7765. self.enable_plots(self.collection.get_list())
  7766. self.inform.emit('[success] %s' %
  7767. _("All plots enabled."))
  7768. def on_enable_sel_plots(self):
  7769. log.debug("App.on_enable_sel_plot()")
  7770. object_list = self.collection.get_selected()
  7771. self.enable_plots(objects=object_list)
  7772. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7773. def on_disable_sel_plots(self):
  7774. log.debug("App.on_disable_sel_plot()")
  7775. # self.inform.emit(_("Disabling plots ..."))
  7776. object_list = self.collection.get_selected()
  7777. self.disable_plots(objects=object_list)
  7778. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7779. def enable_plots(self, objects):
  7780. """
  7781. Enable plots
  7782. :param objects: list of Objects to be enabled
  7783. :return:
  7784. """
  7785. log.debug("Enabling plots ...")
  7786. # self.inform.emit(_("Working ..."))
  7787. for obj in objects:
  7788. if obj.options['plot'] is False:
  7789. obj.options.set_change_callback(lambda x: None)
  7790. obj.options['plot'] = True
  7791. try:
  7792. # only the Gerber obj has on_plot_cb_click() method
  7793. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7794. # disable this cb while disconnected,
  7795. # in case the operation takes time the user is not allowed to change it
  7796. obj.ui.plot_cb.setDisabled(True)
  7797. except AttributeError:
  7798. pass
  7799. obj.set_form_item("plot")
  7800. try:
  7801. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7802. obj.ui.plot_cb.setDisabled(False)
  7803. except AttributeError:
  7804. pass
  7805. obj.options.set_change_callback(obj.on_options_change)
  7806. def worker_task(objs):
  7807. with self.proc_container.new(_("Enabling plots ...")):
  7808. for plot_obj in objs:
  7809. # obj.options['plot'] = True
  7810. if isinstance(plot_obj, CNCJobObject):
  7811. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7812. else:
  7813. plot_obj.plot(visible=True)
  7814. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7815. def disable_plots(self, objects):
  7816. """
  7817. Disables plots
  7818. :param objects: list of Objects to be disabled
  7819. :return:
  7820. """
  7821. # if no objects selected then do nothing
  7822. if not self.collection.get_selected():
  7823. return
  7824. log.debug("Disabling plots ...")
  7825. # self.inform.emit(_("Working ..."))
  7826. for obj in objects:
  7827. if obj.options['plot'] is True:
  7828. obj.options.set_change_callback(lambda x: None)
  7829. obj.options['plot'] = False
  7830. try:
  7831. # only the Gerber obj has on_plot_cb_click() method
  7832. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7833. obj.ui.plot_cb.setDisabled(True)
  7834. except AttributeError:
  7835. pass
  7836. obj.set_form_item("plot")
  7837. try:
  7838. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7839. obj.ui.plot_cb.setDisabled(False)
  7840. except AttributeError:
  7841. pass
  7842. obj.options.set_change_callback(obj.on_options_change)
  7843. try:
  7844. self.delete_selection_shape()
  7845. except Exception as e:
  7846. log.debug("App.disable_plots() --> %s" % str(e))
  7847. def worker_task(objs):
  7848. with self.proc_container.new(_("Disabling plots ...")):
  7849. for plot_obj in objs:
  7850. # obj.options['plot'] = True
  7851. if isinstance(plot_obj, CNCJobObject):
  7852. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7853. else:
  7854. plot_obj.plot(visible=False)
  7855. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7856. def toggle_plots(self, objects):
  7857. """
  7858. Toggle plots visibility
  7859. :param objects: list of Objects for which to be toggled the visibility
  7860. :return: None
  7861. """
  7862. # if no objects selected then do nothing
  7863. if not self.collection.get_selected():
  7864. return
  7865. log.debug("Toggling plots ...")
  7866. self.inform.emit(_("Working ..."))
  7867. for obj in objects:
  7868. if obj.options['plot'] is False:
  7869. obj.options['plot'] = True
  7870. else:
  7871. obj.options['plot'] = False
  7872. self.app_obj.plots_updated.emit()
  7873. def clear_plots(self):
  7874. """
  7875. Clear the plots
  7876. :return: None
  7877. """
  7878. objects = self.collection.get_list()
  7879. for obj in objects:
  7880. obj.clear(obj == objects[-1])
  7881. # Clear pool to free memory
  7882. self.clear_pool()
  7883. def on_set_color_action_triggered(self):
  7884. """
  7885. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  7886. :return:
  7887. """
  7888. new_color = self.defaults['gerber_plot_fill']
  7889. clicked_action = self.sender()
  7890. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  7891. act_name = clicked_action.text()
  7892. sel_obj_list = self.collection.get_selected()
  7893. if not sel_obj_list:
  7894. return
  7895. # a default value, I just chose this one
  7896. alpha_level = 'BF'
  7897. for sel_obj in sel_obj_list:
  7898. if sel_obj.kind == 'excellon':
  7899. alpha_level = str(hex(
  7900. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  7901. elif sel_obj.kind == 'gerber':
  7902. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  7903. elif sel_obj.kind == 'geometry':
  7904. alpha_level = 'FF'
  7905. else:
  7906. log.debug(
  7907. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  7908. continue
  7909. sel_obj.alpha_level = alpha_level
  7910. if act_name == _('Red'):
  7911. new_color = '#FF0000' + alpha_level
  7912. if act_name == _('Blue'):
  7913. new_color = '#0000FF' + alpha_level
  7914. if act_name == _('Yellow'):
  7915. new_color = '#FFDF00' + alpha_level
  7916. if act_name == _('Green'):
  7917. new_color = '#00FF00' + alpha_level
  7918. if act_name == _('Purple'):
  7919. new_color = '#FF00FF' + alpha_level
  7920. if act_name == _('Brown'):
  7921. new_color = '#A52A2A' + alpha_level
  7922. if act_name == _('White'):
  7923. new_color = '#FFFFFF' + alpha_level
  7924. if act_name == _('Black'):
  7925. new_color = '#000000' + alpha_level
  7926. if act_name == _('Custom'):
  7927. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  7928. c_dialog = QtWidgets.QColorDialog()
  7929. plot_fill_color = c_dialog.getColor(initial=new_color)
  7930. if plot_fill_color.isValid() is False:
  7931. return
  7932. new_color = str(plot_fill_color.name()) + alpha_level
  7933. if act_name == _("Default"):
  7934. for sel_obj in sel_obj_list:
  7935. if sel_obj.kind == 'excellon':
  7936. new_color = self.defaults['excellon_plot_fill']
  7937. new_line_color = self.defaults['excellon_plot_line']
  7938. elif sel_obj.kind == 'gerber':
  7939. new_color = self.defaults['gerber_plot_fill']
  7940. new_line_color = self.defaults['gerber_plot_line']
  7941. elif sel_obj.kind == 'geometry':
  7942. new_color = self.defaults['geometry_plot_line']
  7943. new_line_color = self.defaults['geometry_plot_line']
  7944. else:
  7945. log.debug(
  7946. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  7947. continue
  7948. sel_obj.fill_color = new_color
  7949. sel_obj.outline_color = new_line_color
  7950. sel_obj.shapes.redraw(
  7951. update_colors=(new_color, new_line_color)
  7952. )
  7953. return
  7954. if act_name == _("Opacity"):
  7955. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  7956. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  7957. if ok_button:
  7958. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  7959. for sel_obj in sel_obj_list:
  7960. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  7961. sel_obj.shapes.redraw(
  7962. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  7963. )
  7964. return
  7965. new_line_color = color_variant(new_color[:7], 0.7)
  7966. if act_name == _("White"):
  7967. new_line_color = color_variant("#dedede", 0.7)
  7968. for sel_obj in sel_obj_list:
  7969. sel_obj.fill_color = new_color
  7970. sel_obj.outline_color = new_line_color
  7971. sel_obj.shapes.redraw(
  7972. update_colors=(new_color, new_line_color)
  7973. )
  7974. def generate_cnc_job(self, objects):
  7975. """
  7976. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  7977. :param objects: Selected objects in the Project Tab
  7978. :return:
  7979. """
  7980. self.defaults.report_usage("generate_cnc_job()")
  7981. # for obj in objects:
  7982. # obj.generatecncjob()
  7983. for obj in objects:
  7984. obj.on_generatecnc_button_click()
  7985. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  7986. """
  7987. Saves the current project to the specified file.
  7988. :param filename: Name of the file in which to save.
  7989. :type filename: str
  7990. :param quit_action: if the project saving will be followed by an app quit; boolean
  7991. :param silent: if True will not display status messages
  7992. :param from_tcl True is run from Tcl Shell
  7993. :return: None
  7994. """
  7995. self.log.debug("save_project()")
  7996. self.save_in_progress = True
  7997. with self.proc_container.new(_("Saving FlatCAM Project")):
  7998. # Capture the latest changes
  7999. # Current object
  8000. try:
  8001. current_object = self.collection.get_active()
  8002. if current_object:
  8003. current_object.read_form()
  8004. except Exception as e:
  8005. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8006. pass
  8007. # Serialize the whole project
  8008. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8009. "options": self.options,
  8010. "version": self.version}
  8011. if self.defaults["global_save_compressed"] is True:
  8012. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8013. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8014. # # Write
  8015. f.write(g)
  8016. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8017. else:
  8018. # Open file
  8019. try:
  8020. f = open(filename, 'w')
  8021. except IOError:
  8022. App.log.error("Failed to open file for saving: %s", filename)
  8023. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8024. return
  8025. # Write
  8026. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8027. f.close()
  8028. # verification of the saved project
  8029. # Open and parse
  8030. try:
  8031. saved_f = open(filename, 'r')
  8032. except IOError:
  8033. if silent is False:
  8034. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8035. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8036. return
  8037. try:
  8038. saved_d = json.load(saved_f, object_hook=dict2obj)
  8039. except Exception:
  8040. if silent is False:
  8041. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8042. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8043. f.close()
  8044. return
  8045. saved_f.close()
  8046. if silent is False:
  8047. if 'version' in saved_d:
  8048. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8049. else:
  8050. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8051. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8052. tb_settings = QSettings("Open Source", "FlatCAM")
  8053. lock_state = self.ui.lock_action.isChecked()
  8054. tb_settings.setValue('toolbar_lock', lock_state)
  8055. # This will write the setting to the platform specific storage.
  8056. del tb_settings
  8057. # if quit:
  8058. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8059. # t.start()
  8060. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8061. def start_delayed_quit(self, delay, filename, should_quit=None):
  8062. """
  8063. :param delay: period of checking if project file size is more than zero; in seconds
  8064. :param filename: the name of the project file to be checked periodically for size more than zero
  8065. :param should_quit: if the task finished will be followed by an app quit; boolean
  8066. :return:
  8067. """
  8068. to_quit = should_quit
  8069. self.save_timer = QtCore.QTimer()
  8070. self.save_timer.setInterval(delay)
  8071. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8072. self.save_timer.start()
  8073. def check_project_file_size(self, filename, should_quit=None):
  8074. """
  8075. :param filename: the name of the project file to be checked periodically for size more than zero
  8076. :param should_quit: will quit the app if True; boolean
  8077. :return:
  8078. """
  8079. try:
  8080. if os.stat(filename).st_size > 0:
  8081. self.save_in_progress = False
  8082. self.save_timer.stop()
  8083. if should_quit:
  8084. self.app_quit.emit()
  8085. except Exception:
  8086. traceback.print_exc()
  8087. def save_project_auto(self):
  8088. """
  8089. Called periodically to save the project.
  8090. 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
  8091. # progress.
  8092. :return:
  8093. """
  8094. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8095. self.on_file_saveproject()
  8096. def save_project_auto_update(self):
  8097. """
  8098. Update the auto save time interval value.
  8099. :return:
  8100. """
  8101. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8102. try:
  8103. if self.autosave_timer.isActive():
  8104. self.autosave_timer.stop()
  8105. except Exception:
  8106. pass
  8107. if self.defaults['global_autosave'] is True:
  8108. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8109. self.autosave_timer.start()
  8110. def on_options_app2project(self):
  8111. """
  8112. Callback for Options->Transfer Options->App=>Project. Copies options
  8113. from application defaults to project defaults.
  8114. :return: None
  8115. """
  8116. self.defaults.report_usage("on_options_app2project")
  8117. self.preferencesUiManager.defaults_read_form()
  8118. self.options.update(self.defaults)
  8119. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8120. """
  8121. Shows a message on the FlatCAM Shell
  8122. :param msg: Message to display.
  8123. :param show: Opens the shell.
  8124. :param error: Shows the message as an error.
  8125. :param warning: Shows the message as an warning.
  8126. :param success: Shows the message as an success.
  8127. :param selected: Indicate that something was selected on canvas
  8128. :return: None
  8129. """
  8130. if show:
  8131. self.ui.shell_dock.show()
  8132. try:
  8133. if error:
  8134. self.shell.append_error(msg + "\n")
  8135. elif warning:
  8136. self.shell.append_warning(msg + "\n")
  8137. elif success:
  8138. self.shell.append_success(msg + "\n")
  8139. elif selected:
  8140. self.shell.append_selected(msg + "\n")
  8141. else:
  8142. self.shell.append_output(msg + "\n")
  8143. except AttributeError:
  8144. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8145. class ArgsThread(QtCore.QObject):
  8146. open_signal = pyqtSignal(list)
  8147. start = pyqtSignal()
  8148. stop = pyqtSignal()
  8149. if sys.platform == 'win32':
  8150. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8151. else:
  8152. address = ('/tmp/testipc', 'AF_UNIX')
  8153. def __init__(self):
  8154. super(ArgsThread, self).__init__()
  8155. self.listener = None
  8156. self.thread_exit = False
  8157. self.start.connect(self.run)
  8158. self.stop.connect(self.close_listener)
  8159. def my_loop(self, address):
  8160. try:
  8161. self.listener = Listener(*address)
  8162. while self.thread_exit is False:
  8163. conn = self.listener.accept()
  8164. self.serve(conn)
  8165. except socket.error:
  8166. try:
  8167. conn = Client(*address)
  8168. conn.send(sys.argv)
  8169. conn.send('close')
  8170. # close the current instance only if there are args
  8171. if len(sys.argv) > 1:
  8172. try:
  8173. self.listener.close()
  8174. except Exception:
  8175. pass
  8176. sys.exit()
  8177. except ConnectionRefusedError:
  8178. if sys.platform == 'win32':
  8179. pass
  8180. else:
  8181. os.system('rm /tmp/testipc')
  8182. self.listener = Listener(*address)
  8183. while True:
  8184. conn = self.listener.accept()
  8185. self.serve(conn)
  8186. def serve(self, conn):
  8187. while self.thread_exit is False:
  8188. msg = conn.recv()
  8189. if msg == 'close':
  8190. break
  8191. self.open_signal.emit(msg)
  8192. conn.close()
  8193. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8194. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8195. @pyqtSlot()
  8196. def run(self):
  8197. self.my_loop(self.address)
  8198. @pyqtSlot()
  8199. def close_listener(self):
  8200. self.thread_exit = True
  8201. self.listener.close()
  8202. # end of file