FlatCAMApp.py 324 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import urllib.request, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. from stat import S_IREAD, S_IRGRP, S_IROTH
  14. import subprocess
  15. import tkinter as tk
  16. from PyQt5 import QtPrintSupport
  17. import urllib.request, urllib.parse, urllib.error
  18. from contextlib import contextmanager
  19. import gc
  20. from xml.dom.minidom import parseString as parse_xml_string
  21. ########################################
  22. ## Imports part of FlatCAM ##
  23. ########################################
  24. from ObjectCollection import *
  25. from FlatCAMObj import *
  26. from flatcamGUI.PlotCanvas import *
  27. from flatcamGUI.FlatCAMGUI import *
  28. from FlatCAMCommon import LoudDict
  29. from FlatCAMPostProc import load_postprocessors
  30. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  31. from FlatCAMProcess import *
  32. from FlatCAMWorkerStack import WorkerStack
  33. from flatcamGUI.VisPyVisuals import Color
  34. from vispy.gloo.util import _screenshot
  35. from vispy.io import write_png
  36. from flatcamTools import *
  37. from multiprocessing import Pool
  38. import tclCommands
  39. import gettext
  40. import FlatCAMTranslation as fcTranslate
  41. fcTranslate.apply_language('strings')
  42. import builtins
  43. if '_' not in builtins.__dict__:
  44. _ = gettext.gettext
  45. ########################################
  46. ## App ##
  47. ########################################
  48. class App(QtCore.QObject):
  49. """
  50. The main application class. The constructor starts the GUI.
  51. """
  52. # Get Cmd Line Options
  53. cmd_line_shellfile = ''
  54. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  55. try:
  56. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  57. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  58. except getopt.GetoptError:
  59. print(cmd_line_help)
  60. sys.exit(2)
  61. for opt, arg in cmd_line_options:
  62. if opt == '-h':
  63. print(cmd_line_help)
  64. sys.exit()
  65. elif opt == '--shellfile':
  66. cmd_line_shellfile = arg
  67. # Logging ##
  68. log = logging.getLogger('base')
  69. log.setLevel(logging.DEBUG)
  70. # log.setLevel(logging.WARNING)
  71. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  72. handler = logging.StreamHandler()
  73. handler.setFormatter(formatter)
  74. log.addHandler(handler)
  75. # Version
  76. version = 8.912
  77. version_date = "2019/03/17"
  78. beta = True
  79. # current date now
  80. date = str(datetime.today()).rpartition(' ')[0]
  81. # URL for update checks and statistics
  82. version_url = "http://flatcam.org/version"
  83. # App URL
  84. app_url = "http://flatcam.org"
  85. # Manual URL
  86. manual_url = "http://flatcam.org/manual/index.html"
  87. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  88. should_we_quit = True
  89. # this variable will hold the project status
  90. # if True it will mean that the project was modified and not saved
  91. should_we_save = False
  92. ##################
  93. ## Signals ##
  94. ##################
  95. # Inform the user
  96. # Handled by:
  97. # * App.info() --> Print on the status bar
  98. inform = QtCore.pyqtSignal(str)
  99. # General purpose background task
  100. worker_task = QtCore.pyqtSignal(dict)
  101. # File opened
  102. # Handled by:
  103. # * register_folder()
  104. # * register_recent()
  105. # Note: Setting the parameters to unicode does not seem
  106. # to have an effect. Then are received as Qstring
  107. # anyway.
  108. # File type and filename
  109. file_opened = QtCore.pyqtSignal(str, str)
  110. # File type and filename
  111. file_saved = QtCore.pyqtSignal(str, str)
  112. # Percentage of progress
  113. progress = QtCore.pyqtSignal(int)
  114. plots_updated = QtCore.pyqtSignal()
  115. # Emitted by new_object() and passes the new object as argument, plot flag.
  116. # on_object_created() adds the object to the collection, plots on appropriate flag
  117. # and emits new_object_available.
  118. object_created = QtCore.pyqtSignal(object, bool, bool)
  119. # Emitted when a object has been changed (like scaled, mirrored)
  120. object_changed = QtCore.pyqtSignal(object)
  121. # Emitted after object has been plotted.
  122. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  123. object_plotted = QtCore.pyqtSignal(object)
  124. # Emitted when a new object has been added or deleted from/to the collection
  125. object_status_changed = QtCore.pyqtSignal(object, str)
  126. message = QtCore.pyqtSignal(str, str, str)
  127. # Emmited when shell command is finished(one command only)
  128. shell_command_finished = QtCore.pyqtSignal(object)
  129. # Emitted when multiprocess pool has been recreated
  130. pool_recreated = QtCore.pyqtSignal(object)
  131. # Emitted when an unhandled exception happens
  132. # in the worker task.
  133. thread_exception = QtCore.pyqtSignal(object)
  134. def __init__(self, user_defaults=True, post_gui=None):
  135. """
  136. Starts the application.
  137. :return: app
  138. :rtype: App
  139. """
  140. App.log.info("FlatCAM Starting...")
  141. ###################
  142. ### OS-specific ###
  143. ###################
  144. # Folder for user settings.
  145. if sys.platform == 'win32':
  146. from win32com.shell import shell, shellcon
  147. if platform.architecture()[0] == '32bit':
  148. App.log.debug("Win32!")
  149. else:
  150. App.log.debug("Win64!")
  151. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\FlatCAM'
  152. self.os = 'windows'
  153. else: # Linux/Unix/MacOS
  154. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  155. self.os = 'unix'
  156. ###############################
  157. ### Setup folders and files ###
  158. ###############################
  159. if not os.path.exists(self.data_path):
  160. os.makedirs(self.data_path)
  161. App.log.debug('Created data folder: ' + self.data_path)
  162. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  163. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  164. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  165. if not os.path.exists(self.postprocessorpaths):
  166. os.makedirs(self.postprocessorpaths)
  167. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  168. # create current_defaults.FlatConfig file if there is none
  169. try:
  170. f = open(self.data_path + '/current_defaults.FlatConfig')
  171. f.close()
  172. except IOError:
  173. App.log.debug('Creating empty current_defaults.FlatConfig')
  174. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  175. json.dump({}, f)
  176. f.close()
  177. # create factory_defaults.FlatConfig file if there is none
  178. try:
  179. f = open(self.data_path + '/factory_defaults.FlatConfig')
  180. f.close()
  181. except IOError:
  182. App.log.debug('Creating empty factory_defaults.FlatConfig')
  183. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  184. json.dump({}, f)
  185. f.close()
  186. try:
  187. f = open(self.data_path + '/recent.json')
  188. f.close()
  189. except IOError:
  190. App.log.debug('Creating empty recent.json')
  191. f = open(self.data_path + '/recent.json', 'w')
  192. json.dump([], f)
  193. f.close()
  194. # Application directory. CHDIR to it. Otherwise, trying to load
  195. # GUI icons will fail as their path is relative.
  196. # This will fail under cx_freeze ...
  197. self.app_home = os.path.dirname(os.path.realpath(__file__))
  198. App.log.debug("Application path is " + self.app_home)
  199. App.log.debug("Started in " + os.getcwd())
  200. # cx_freeze workaround
  201. if os.path.isfile(self.app_home):
  202. self.app_home = os.path.dirname(self.app_home)
  203. os.chdir(self.app_home)
  204. # Create multiprocessing pool
  205. self.pool = Pool()
  206. # variable to store mouse coordinates
  207. self.mouse = [0, 0]
  208. ####################
  209. ## Initialize GUI ##
  210. ####################
  211. # FlatCAM colors used in plotting
  212. self.FC_light_green = '#BBF268BF'
  213. self.FC_dark_green = '#006E20BF'
  214. self.FC_light_blue = '#a5a5ffbf'
  215. self.FC_dark_blue = '#0000ffbf'
  216. QtCore.QObject.__init__(self)
  217. self.ui = FlatCAMGUI(self.version, self.beta, self)
  218. # self.connect(self.ui,
  219. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  220. # self.save_geometry) PyQt4
  221. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  222. self.ui.final_save.connect(self.final_save)
  223. ##############
  224. #### Data ####
  225. ##############
  226. self.recent = []
  227. self.clipboard = QtWidgets.QApplication.clipboard()
  228. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  229. self.project_filename = None
  230. self.toggle_units_ignore = False
  231. # self.defaults_form = PreferencesUI()
  232. # when adding entries here read the comments in the method found bellow named:
  233. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  234. self.defaults_form_fields = {
  235. # General App
  236. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  237. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  238. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  239. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  240. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  241. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  242. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  243. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  244. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  245. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  246. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  247. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  248. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  249. # General GUI Preferences
  250. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  251. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  252. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  253. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  254. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  255. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  256. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  257. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  258. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  259. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  260. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  261. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  262. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  263. # General GUI Settings
  264. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  265. # Gerber General
  266. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  267. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  268. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  269. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  270. # Gerber Options
  271. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  272. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  273. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  274. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  275. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  276. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  277. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  278. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  279. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  280. # Gerber Advanced Options
  281. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  282. "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  283. "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  284. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  285. # Excellon General
  286. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  287. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  288. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  289. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  290. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  291. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  292. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  293. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  294. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  295. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  296. # Excellon Options
  297. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  298. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  299. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  300. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  301. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  302. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  303. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  304. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  305. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  306. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  307. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  308. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  309. # Excellon Advanced Options
  310. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  311. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  312. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  313. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  314. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  315. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  316. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  317. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  318. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  319. # Excellon Export
  320. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  321. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  322. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  323. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  324. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  325. # Geometry General
  326. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  327. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  328. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  329. # Geometry Options
  330. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  331. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  332. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  333. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  334. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  335. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  336. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  337. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  338. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  339. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  340. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  341. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  342. # Geometry Advanced Options
  343. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  344. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  345. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  346. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  347. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  348. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  349. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  350. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  351. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  352. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  353. # CNCJob General
  354. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  355. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  356. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  357. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  358. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  359. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  360. # CNC Job Options
  361. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  362. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  363. # CNC Job Advanced Options
  364. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  365. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  366. # NCC Tool
  367. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  368. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  369. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  370. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  371. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  372. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  373. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  374. # CutOut Tool
  375. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  376. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  377. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  378. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  379. # Paint Area Tool
  380. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  381. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  382. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  383. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  384. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  385. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  386. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  387. # 2-sided Tool
  388. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  389. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  390. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  391. # Film Tool
  392. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  393. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  394. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  395. # Panelize Tool
  396. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  397. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  398. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  399. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  400. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  401. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  402. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  403. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  404. # Calculators Tool
  405. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  406. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  407. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  408. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  409. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  410. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  411. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  412. # Transformations Tool
  413. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  414. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  415. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  416. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  417. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  418. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  419. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  420. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  421. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  422. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  423. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  424. # SolderPaste Dispensing Tool
  425. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  426. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  427. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  428. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  429. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  430. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  431. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  432. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  433. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  434. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  435. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  436. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  437. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  438. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  439. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  440. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  441. }
  442. #############################
  443. #### LOAD POSTPROCESSORS ####
  444. #############################
  445. self.postprocessors = load_postprocessors(self)
  446. for name in list(self.postprocessors.keys()):
  447. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  448. if name.partition('_')[0] == 'Paste':
  449. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  450. continue
  451. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  452. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  453. if name == 'hpgl':
  454. continue
  455. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  456. #############################
  457. #### LOAD LANGUAGES ####
  458. #############################
  459. self.languages = fcTranslate.load_languages()
  460. for name in sorted(self.languages.values()):
  461. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  462. self.defaults = LoudDict()
  463. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  464. self.defaults.update({
  465. # Global APP Preferences
  466. "global_serial": 0,
  467. "global_stats": {},
  468. "units": "IN",
  469. "global_app_level": 'b',
  470. "global_language": 'English',
  471. "global_version_check": True,
  472. "global_send_stats": True,
  473. "global_pan_button": '2',
  474. "global_mselect_key": 'Control',
  475. "global_project_at_startup": False,
  476. "global_project_autohide": True,
  477. "global_toggle_tooltips": True,
  478. "global_compression_level": 3,
  479. "global_save_compressed": True,
  480. # Global GUI Preferences
  481. "global_gridx": 0.0393701,
  482. "global_gridy": 0.0393701,
  483. "global_snap_max": 0.001968504,
  484. "global_workspace": False,
  485. "global_workspaceT": "A4P",
  486. "global_grid_context_menu": {
  487. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  488. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  489. },
  490. "global_plot_fill": '#BBF268BF',
  491. "global_plot_line": '#006E20BF',
  492. "global_sel_fill": '#a5a5ffbf',
  493. "global_sel_line": '#0000ffbf',
  494. "global_alt_sel_fill": '#BBF268BF',
  495. "global_alt_sel_line": '#006E20BF',
  496. "global_draw_color": '#FF0000',
  497. "global_sel_draw_color": '#0000FF',
  498. "global_toolbar_view": 127,
  499. "global_background_timeout": 300000, # Default value is 5 minutes
  500. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  501. # (python trace only for unknown errors),
  502. # 1 = show trace(show trace allways),
  503. # 2 = (For the future).
  504. # Persistence
  505. "global_last_folder": None,
  506. "global_last_save_folder": None,
  507. # Default window geometry
  508. "global_def_win_x": 100,
  509. "global_def_win_y": 100,
  510. "global_def_win_w": 1024,
  511. "global_def_win_h": 650,
  512. # Constants...
  513. "global_defaults_save_period_ms": 20000, # Time between default saves.
  514. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  515. "global_shell_at_startup": False, # Show the shell at startup.
  516. "global_recent_limit": 10, # Max. items in recent list.
  517. "fit_key": 'V',
  518. "zoom_out_key": '-',
  519. "zoom_in_key": '=',
  520. "grid_toggle_key": 'G',
  521. "zoom_ratio": 1.5,
  522. "global_point_clipboard_format": "(%.4f, %.4f)",
  523. "global_zdownrate": None,
  524. # General GUI Settings
  525. "global_hover": True,
  526. # Gerber General
  527. "gerber_plot": True,
  528. "gerber_solid": True,
  529. "gerber_multicolored": False,
  530. "gerber_isotooldia": 0.016,
  531. "gerber_isopasses": 1,
  532. "gerber_isooverlap": 0.15,
  533. # Gerber Options
  534. "gerber_combine_passes": False,
  535. "gerber_milling_type": "cl",
  536. "gerber_noncoppermargin": 0.1,
  537. "gerber_noncopperrounded": False,
  538. "gerber_bboxmargin": 0.1,
  539. "gerber_bboxrounded": False,
  540. "gerber_circle_steps": 64,
  541. "gerber_use_buffer_for_union": True,
  542. # Gerber Advanced Options
  543. "gerber_aperture_display": False,
  544. "gerber_aperture_scale_factor": 1.0,
  545. "gerber_aperture_buffer_factor": 0.0,
  546. "gerber_follow": False,
  547. # Excellon General
  548. "excellon_plot": True,
  549. "excellon_solid": True,
  550. "excellon_format_upper_in": 2,
  551. "excellon_format_lower_in": 4,
  552. "excellon_format_upper_mm": 3,
  553. "excellon_format_lower_mm": 3,
  554. "excellon_zeros": "L",
  555. "excellon_units": "INCH",
  556. "excellon_optimization_type": 'B',
  557. "excellon_search_time": 3,
  558. # Excellon Options
  559. "excellon_drillz": -0.1,
  560. "excellon_travelz": 0.1,
  561. "excellon_feedrate": 3.0,
  562. "excellon_spindlespeed": None,
  563. "excellon_dwell": False,
  564. "excellon_dwelltime": 1,
  565. "excellon_toolchange": False,
  566. "excellon_toolchangez": 1.0,
  567. "excellon_ppname_e": 'default',
  568. "excellon_tooldia": 0.016,
  569. "excellon_slot_tooldia": 0.016,
  570. "excellon_gcode_type": "drills",
  571. # Excellon Advanced Options
  572. "excellon_offset": 0.0,
  573. "excellon_toolchangexy": "0.0, 0.0",
  574. "excellon_startz": None,
  575. "excellon_endz": 2.0,
  576. "excellon_feedrate_rapid": 3.0,
  577. "excellon_z_pdepth": -0.02,
  578. "excellon_feedrate_probe": 3.0,
  579. "excellon_f_plunge": False,
  580. "excellon_f_retract": False,
  581. # Excellon Export
  582. "excellon_exp_units": 'INCH',
  583. "excellon_exp_format": 'ndec',
  584. "excellon_exp_integer": 2,
  585. "excellon_exp_decimals": 4,
  586. "excellon_exp_zeros": 'LZ',
  587. # Geometry General
  588. "geometry_plot": True,
  589. "geometry_circle_steps": 64,
  590. "geometry_cnctooldia": 0.016,
  591. # Geometry Options
  592. "geometry_cutz": -0.002,
  593. "geometry_multidepth": False,
  594. "geometry_depthperpass": 0.002,
  595. "geometry_travelz": 0.1,
  596. "geometry_toolchange": False,
  597. "geometry_toolchangez": 1.0,
  598. "geometry_feedrate": 3.0,
  599. "geometry_feedrate_z": 3.0,
  600. "geometry_spindlespeed": None,
  601. "geometry_dwell": False,
  602. "geometry_dwelltime": 1,
  603. "geometry_ppname_g": 'default',
  604. # Geometry Advanced Options
  605. "geometry_toolchangexy": "0.0, 0.0",
  606. "geometry_startz": None,
  607. "geometry_endz": 2.0,
  608. "geometry_feedrate_rapid": 3.0,
  609. "geometry_extracut": False,
  610. "geometry_z_pdepth": -0.02,
  611. "geometry_f_plunge": False,
  612. "geometry_feedrate_probe": 3.0,
  613. "geometry_segx": 0.0,
  614. "geometry_segy": 0.0,
  615. # CNC Job General
  616. "cncjob_plot": True,
  617. "cncjob_plot_kind": 'all',
  618. "cncjob_tooldia": 0.0393701,
  619. "cncjob_coords_decimals": 4,
  620. "cncjob_fr_decimals": 2,
  621. "cncjob_steps_per_circle": 64,
  622. # CNC Job Options
  623. "cncjob_prepend": "",
  624. "cncjob_append": "",
  625. # CNC Job Advanced Options
  626. "cncjob_toolchange_macro": "",
  627. "cncjob_toolchange_macro_enable": False,
  628. "tools_ncctools": "0.0393701, 0.019685",
  629. "tools_nccoverlap": 0.015748,
  630. "tools_nccmargin": 0.00393701,
  631. "tools_nccmethod": "seed",
  632. "tools_nccconnect": True,
  633. "tools_ncccontour": True,
  634. "tools_nccrest": False,
  635. "tools_cutouttooldia": 0.00393701,
  636. "tools_cutoutmargin": 0.00393701,
  637. "tools_cutoutgapsize": 0.005905512,
  638. "tools_gaps_ff": "8",
  639. "tools_painttooldia": 0.07,
  640. "tools_paintoverlap": 0.15,
  641. "tools_paintmargin": 0.0,
  642. "tools_paintmethod": "seed",
  643. "tools_selectmethod": "single",
  644. "tools_pathconnect": True,
  645. "tools_paintcontour": True,
  646. "tools_2sided_mirror_axis": "X",
  647. "tools_2sided_axis_loc": "point",
  648. "tools_2sided_drilldia": 0.0393701,
  649. "tools_film_type": 'neg',
  650. "tools_film_boundary": 0.0393701,
  651. "tools_film_scale": 0,
  652. "tools_panelize_spacing_columns": 0,
  653. "tools_panelize_spacing_rows": 0,
  654. "tools_panelize_columns": 1,
  655. "tools_panelize_rows": 1,
  656. "tools_panelize_constrain": False,
  657. "tools_panelize_constrainx": 0.0,
  658. "tools_panelize_constrainy": 0.0,
  659. "tools_panelize_panel_type": 'gerber',
  660. "tools_calc_vshape_tip_dia": 0.007874,
  661. "tools_calc_vshape_tip_angle": 30,
  662. "tools_calc_vshape_cut_z": 0.000787,
  663. "tools_calc_electro_length": 10.0,
  664. "tools_calc_electro_width": 10.0,
  665. "tools_calc_electro_cdensity":13.0,
  666. "tools_calc_electro_growth": 10.0,
  667. "tools_transform_rotate": 90,
  668. "tools_transform_skew_x": 0.0,
  669. "tools_transform_skew_y": 0.0,
  670. "tools_transform_scale_x": 1.0,
  671. "tools_transform_scale_y": 1.0,
  672. "tools_transform_scale_link": True,
  673. "tools_transform_scale_reference": True,
  674. "tools_transform_offset_x": 0.0,
  675. "tools_transform_offset_y": 0.0,
  676. "tools_transform_mirror_reference": False,
  677. "tools_transform_mirror_point": (0, 0),
  678. "tools_solderpaste_tools": "0.0393701, 0.011811",
  679. "tools_solderpaste_new": 0.011811,
  680. "tools_solderpaste_z_start": 0.00019685039,
  681. "tools_solderpaste_z_dispense": 0.00393701,
  682. "tools_solderpaste_z_stop": 0.00019685039,
  683. "tools_solderpaste_z_travel": 0.00393701,
  684. "tools_solderpaste_z_toolchange": 0.0393701,
  685. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  686. "tools_solderpaste_frxy": 3.0,
  687. "tools_solderpaste_frz": 3.0,
  688. "tools_solderpaste_frz_dispense": 0.0393701,
  689. "tools_solderpaste_speedfwd": 20,
  690. "tools_solderpaste_dwellfwd": 1,
  691. "tools_solderpaste_speedrev": 10,
  692. "tools_solderpaste_dwellrev": 1,
  693. "tools_solderpaste_pp": 'Paste_1'
  694. })
  695. ###############################
  696. ### Load defaults from file ###
  697. ###############################
  698. if user_defaults:
  699. self.load_defaults(filename='current_defaults')
  700. ############################
  701. ##### APPLY APP LANGUAGE ###
  702. ############################
  703. ret_val = fcTranslate.apply_language('strings')
  704. if ret_val == "no language":
  705. self.inform.emit(_("[ERROR] Could not find the Language files. The App strings are missing."))
  706. log.debug("Could not find the Language files. The App strings are missing.")
  707. else:
  708. # make the current language the current selection on the language combobox
  709. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  710. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  711. ###################################
  712. ### CREATE UNIQUE SERIAL NUMBER ###
  713. ###################################
  714. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  715. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  716. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  717. self.save_defaults(silent=True)
  718. self.propagate_defaults(silent=True)
  719. self.restore_main_win_geom()
  720. def auto_save_defaults():
  721. try:
  722. self.save_defaults(silent=True)
  723. self.propagate_defaults(silent=True)
  724. finally:
  725. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  726. # the following lines activates automatic defaults save
  727. # if user_defaults:
  728. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  729. # self.options_form = PreferencesUI()
  730. self.options_form_fields = {
  731. "units": self.ui.general_options_form.general_app_group.units_radio,
  732. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  733. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  734. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  735. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  736. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  737. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  738. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  739. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  740. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  741. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  742. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  743. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  744. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  745. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  746. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  747. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  748. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  749. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  750. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  751. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  752. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  753. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  754. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  755. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  756. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  757. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  758. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  759. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  760. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  761. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  762. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  763. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  764. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  765. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  766. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  767. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  768. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  769. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  770. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  771. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  772. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  773. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  774. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  775. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  776. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  777. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  778. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  779. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  780. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  781. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  782. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  783. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  784. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  785. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  786. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  787. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  788. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  789. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  790. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  791. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  792. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  793. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  794. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  795. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  796. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  797. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  798. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  799. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  800. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  801. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  802. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  803. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  804. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  805. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  806. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  807. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  808. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  809. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  810. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  811. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  812. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  813. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  814. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  815. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  816. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  817. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  818. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  819. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  820. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  821. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  822. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  823. }
  824. for name in list(self.postprocessors.keys()):
  825. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  826. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  827. self.options = LoudDict()
  828. self.options.set_change_callback(self.on_options_dict_change)
  829. self.options.update({
  830. "units": "IN",
  831. "global_gridx": 1.0,
  832. "global_gridy": 1.0,
  833. "global_snap_max": 0.05,
  834. "global_background_timeout": 300000, # Default value is 5 minutes
  835. "global_verbose_error_level": 0, # Shell verbosity:
  836. # 0 = default(python trace only for unknown errors),
  837. # 1 = show trace(show trace allways), 2 = (For the future).
  838. "gerber_plot": True,
  839. "gerber_solid": True,
  840. "gerber_multicolored": False,
  841. "gerber_isotooldia": 0.016,
  842. "gerber_isopasses": 1,
  843. "gerber_isooverlap": 0.15,
  844. "gerber_combine_passes": True,
  845. "gerber_noncoppermargin": 0.0,
  846. "gerber_noncopperrounded": False,
  847. "gerber_bboxmargin": 0.0,
  848. "gerber_bboxrounded": False,
  849. "excellon_plot": True,
  850. "excellon_solid": False,
  851. "excellon_format_upper_in": 2,
  852. "excellon_format_lower_in": 4,
  853. "excellon_format_upper_mm": 3,
  854. "excellon_format_lower_mm": 3,
  855. "excellon_units": 'INCH',
  856. "excellon_optimization_type": 'B',
  857. "excellon_search_time": 3,
  858. "excellon_zeros": "L",
  859. "excellon_drillz": -0.1,
  860. "excellon_travelz": 0.1,
  861. "excellon_feedrate": 3.0,
  862. "excellon_feedrate_rapid": 3.0,
  863. "excellon_spindlespeed": None,
  864. "excellon_dwell": True,
  865. "excellon_dwelltime": 1000,
  866. "excellon_toolchange": False,
  867. "excellon_toolchangez": 1.0,
  868. "excellon_toolchangexy": "0.0, 0.0",
  869. "excellon_tooldia": 0.016,
  870. "excellon_ppname_e": 'default',
  871. "excellon_f_plunge": False,
  872. "excellon_startz": None,
  873. "excellon_endz": 2.0,
  874. "geometry_plot": True,
  875. "geometry_segx": 0.0,
  876. "geometry_segy": 0.0,
  877. "geometry_cutz": -0.002,
  878. "geometry_travelz": 0.1,
  879. "geometry_feedrate": 3.0,
  880. "geometry_feedrate_z": 3.0,
  881. "geometry_feedrate_rapid": 3.0,
  882. "geometry_spindlespeed": None,
  883. "geometry_dwell": True,
  884. "geometry_dwelltime": 1000,
  885. "geometry_cnctooldia": 0.016,
  886. "geometry_toolchange": False,
  887. "geometry_toolchangez": 2.0,
  888. "geometry_toolchangexy": "0.0, 0.0",
  889. "geometry_startz": None,
  890. "geometry_endz": 2.0,
  891. "geometry_ppname_g": "default",
  892. "geometry_f_plunge": False,
  893. "geometry_depthperpass": 0.002,
  894. "geometry_multidepth": False,
  895. "geometry_extracut": False,
  896. "cncjob_plot": True,
  897. "cncjob_tooldia": 0.016,
  898. "cncjob_prepend": "",
  899. "cncjob_append": "",
  900. "tools_ncctools": "1.0, 0.5",
  901. "tools_nccoverlap": 0.4,
  902. "tools_nccmargin": 1,
  903. "tools_cutouttooldia": 0.07,
  904. "tools_cutoutmargin": 0.1,
  905. "tools_cutoutgapsize": 0.15,
  906. "tools_gaps_ff": "8",
  907. "tools_painttooldia": 0.07,
  908. "tools_paintoverlap": 0.15,
  909. "tools_paintmargin": 0.0,
  910. "tools_paintmethod": "seed",
  911. "tools_selectmethod": "single",
  912. "tools_pathconnect": True,
  913. "tools_paintcontour": True,
  914. "tools_2sided_mirror_axis": "X",
  915. "tools_2sided_axis_loc": 'point',
  916. "tools_2sided_drilldia": 1,
  917. "tools_film_type": 'neg',
  918. "tools_film_boundary": 1,
  919. "tools_film_scale": 0,
  920. "tools_panelize_spacing_columns": 0,
  921. "tools_panelize_spacing_rows": 0,
  922. "tools_panelize_columns": 1,
  923. "tools_panelize_rows": 1,
  924. "tools_panelize_constrain": False,
  925. "tools_panelize_constrainx": 0.0,
  926. "tools_panelize_constrainy": 0.0
  927. })
  928. self.options.update(self.defaults) # Copy app defaults to project options
  929. self.gen_form = None
  930. self.ger_form = None
  931. self.exc_form = None
  932. self.geo_form = None
  933. self.cnc_form = None
  934. self.tools_form = None
  935. self.on_options_combo_change(0) # Will show the initial form
  936. ### Define OBJECT COLLECTION ###
  937. self.collection = ObjectCollection(self)
  938. self.ui.project_tab_layout.addWidget(self.collection.view)
  939. ###
  940. self.log.debug("Finished creating Object Collection.")
  941. ### Initialize the color box's color in Preferences -> Global -> Color
  942. # Init Plot Colors
  943. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  944. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  945. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  946. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  947. int(self.defaults['global_plot_fill'][7:9], 16))
  948. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  949. int(self.defaults['global_plot_fill'][7:9], 16))
  950. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  951. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  952. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  953. # Init Left-Right Selection colors
  954. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  955. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  956. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  957. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  958. int(self.defaults['global_sel_fill'][7:9], 16))
  959. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  960. int(self.defaults['global_sel_fill'][7:9], 16))
  961. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  962. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  963. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  964. # Init Right-Left Selection colors
  965. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  966. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  967. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  968. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  969. int(self.defaults['global_sel_fill'][7:9], 16))
  970. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  971. int(self.defaults['global_sel_fill'][7:9], 16))
  972. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  973. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  974. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  975. # Init Draw color and Selection Draw Color
  976. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  977. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  978. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  979. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  980. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  981. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  982. #### End of Data ####
  983. #### Plot Area ####
  984. start_plot_time = time.time() # debug
  985. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  986. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  987. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  988. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  989. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  990. # Keys over plot enabled
  991. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  992. self.ui.splitter.setStretchFactor(1, 2)
  993. # So it can receive key presses
  994. self.plotcanvas.vispy_canvas.native.setFocus()
  995. self.app_cursor = self.plotcanvas.new_cursor()
  996. self.app_cursor.enabled = False
  997. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  998. # depending on from where those tools are called different actions can be done
  999. self.call_source = 'app'
  1000. end_plot_time = time.time()
  1001. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  1002. ### EDITOR section
  1003. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  1004. self.exc_editor = FlatCAMExcEditor(self)
  1005. #### Adjust tabs width ####
  1006. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1007. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1008. self.collection.view.setMinimumWidth(290)
  1009. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  1010. #### Worker ####
  1011. self.workers = WorkerStack()
  1012. self.worker_task.connect(self.workers.add_task)
  1013. ### Signal handling ###
  1014. ## Custom signals
  1015. self.inform.connect(self.info)
  1016. self.message.connect(self.message_dialog)
  1017. self.progress.connect(self.set_progress_bar)
  1018. self.object_created.connect(self.on_object_created)
  1019. self.object_changed.connect(self.on_object_changed)
  1020. self.object_plotted.connect(self.on_object_plotted)
  1021. self.plots_updated.connect(self.on_plots_updated)
  1022. self.file_opened.connect(self.register_recent)
  1023. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1024. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1025. ## Standard signals
  1026. # Menu
  1027. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1028. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1029. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1030. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1031. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1032. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1033. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1034. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1035. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1036. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1037. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1038. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1039. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1040. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1041. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1042. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1043. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1044. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1045. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1046. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1047. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1048. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  1049. self.ui.menueditedit.triggered.connect(self.object2editor)
  1050. self.ui.menueditok.triggered.connect(self.editor2object)
  1051. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1052. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1053. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1054. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1055. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1056. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1057. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1058. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  1059. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1060. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1061. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1062. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1063. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1064. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1065. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1066. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1067. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1068. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1069. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1070. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1071. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1072. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1073. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1074. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1075. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1076. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1077. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1078. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1079. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1080. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1081. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1082. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1083. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1084. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1085. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1086. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1087. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1088. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1089. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1090. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1091. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1092. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1093. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1094. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1095. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1096. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1097. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1098. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1099. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1100. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1101. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1102. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1103. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1104. # ToolBar signals
  1105. self.connect_toolbar_signals()
  1106. # Context Menu
  1107. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1108. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1109. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1110. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1111. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  1112. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  1113. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  1114. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  1115. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  1116. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  1117. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  1118. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1119. self.ui.clearplot.triggered.connect(self.clear_plots)
  1120. self.ui.replot.triggered.connect(self.plot_all)
  1121. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1122. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1123. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1124. self.ui.popmenu_save.triggered.connect(self.editor2object)
  1125. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1126. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1127. # Preferences Plot Area TAB
  1128. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1129. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1130. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1131. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1132. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1133. ###############################
  1134. ### GUI PREFERENCES SIGNALS ###
  1135. ###############################
  1136. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1137. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1138. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1139. )
  1140. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(self.on_toggle_units)
  1141. ###############################
  1142. ### GUI PREFERENCES SIGNALS ###
  1143. ###############################
  1144. # Setting plot colors signals
  1145. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1146. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1147. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1148. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1149. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1150. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1151. # Setting selection (left - right) colors signals
  1152. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1153. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1154. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1155. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1156. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1157. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1158. # Setting selection (right - left) colors signals
  1159. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1160. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1161. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1162. self.on_alt_sf_color_spinner)
  1163. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1164. self.on_alt_sf_color_slider)
  1165. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1166. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1167. # Setting Editor Draw colors signals
  1168. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1169. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1170. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1171. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1172. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1173. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1174. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1175. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1176. self.on_cnc_custom_parameters)
  1177. # Modify G-CODE Plot Area TAB
  1178. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1179. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1180. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1181. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1182. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1183. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1184. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1185. # Object list
  1186. self.collection.view.activated.connect(self.on_row_activated)
  1187. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1188. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1189. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1190. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1191. self.on_excellon_defaults_button)
  1192. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1193. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1194. self.on_excellon_options_button)
  1195. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1196. self.tool_tab_locked = False
  1197. # decide if to show or hide the Notebook side of the screen at startup
  1198. if self.defaults["global_project_at_startup"] is True:
  1199. self.ui.splitter.setSizes([1, 1])
  1200. else:
  1201. self.ui.splitter.setSizes([0, 1])
  1202. ####################
  1203. ### Other setups ###
  1204. ####################
  1205. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1206. self.setup_obj_classes()
  1207. self.setup_recent_items()
  1208. self.setup_component_editor()
  1209. #############
  1210. ### Shell ###
  1211. #############
  1212. ###
  1213. # Auto-complete KEYWORDS
  1214. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1215. 'aligndrill', 'clear',
  1216. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1217. 'export_gcode',
  1218. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1219. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1220. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1221. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1222. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1223. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1224. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1225. ]
  1226. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1227. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1228. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1229. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1230. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1231. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1232. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1233. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1234. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1235. ]
  1236. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1237. self.shell = FCShell(self, version=self.version)
  1238. self.shell._edit.set_model_data(self.myKeywords)
  1239. self.shell.setWindowIcon(self.ui.app_icon)
  1240. self.shell.setWindowTitle("FlatCAM Shell")
  1241. self.shell.resize(*self.defaults["global_shell_shape"])
  1242. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1243. self.shell.append_output("(Type help to get started)\n\n")
  1244. self.init_tcl()
  1245. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1246. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1247. self.ui.shell_dock.setWidget(self.shell)
  1248. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1249. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1250. QtWidgets.QDockWidget.DockWidgetFloatable |
  1251. QtWidgets.QDockWidget.DockWidgetClosable)
  1252. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1253. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1254. if self.defaults["global_shell_at_startup"]:
  1255. self.ui.shell_dock.show()
  1256. else:
  1257. self.ui.shell_dock.hide()
  1258. #########################
  1259. ### Tools and Plugins ###
  1260. #########################
  1261. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1262. self.install_tools()
  1263. ### System Font Parsing ###
  1264. # self.f_parse = ParseFont(self)
  1265. # self.parse_system_fonts()
  1266. # test if the program was started with a script as parameter
  1267. if self.cmd_line_shellfile:
  1268. try:
  1269. with open(self.cmd_line_shellfile, "r") as myfile:
  1270. cmd_line_shellfile_text = myfile.read()
  1271. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1272. except Exception as ext:
  1273. print("ERROR: ", ext)
  1274. sys.exit(2)
  1275. ###########################
  1276. #### Check for updates ####
  1277. ###########################
  1278. # Separate thread (Not worker)
  1279. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1280. if (self.beta is False or self.beta is None) and \
  1281. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1282. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1283. self.thr2 = QtCore.QThread()
  1284. self.worker_task.emit({'fcn': self.version_check,
  1285. 'params': []})
  1286. self.thr2.start()
  1287. ####################################
  1288. #### Variables for global usage ####
  1289. ####################################
  1290. # coordinates for relative position display
  1291. self.rel_point1 = (0, 0)
  1292. self.rel_point2 = (0, 0)
  1293. # variable to store coordinates
  1294. self.pos = (0, 0)
  1295. self.pos_jump = (0, 0)
  1296. # decide if we have a double click or single click
  1297. self.doubleclick = False
  1298. # variable to store if there was motion before right mouse button click (panning)
  1299. self.panning_action = False
  1300. # variable to store if a command is active (then the var is not None) and which one it is
  1301. self.command_active = None
  1302. # variable to store the status of moving selection action
  1303. # None value means that it's not an selection action
  1304. # True value = a selection from left to right
  1305. # False value = a selection from right to left
  1306. self.selection_type = None
  1307. # List to store the objects that are currently loaded in FlatCAM
  1308. # This list is updated on each object creation or object delete
  1309. self.all_objects_list = []
  1310. # List to store the objects that are selected
  1311. self.sel_objects_list = []
  1312. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1313. self.key_modifiers = None
  1314. # Variable to hold the status of the axis
  1315. self.toggle_axis = True
  1316. # Variable to store the status of the fullscreen event
  1317. self.toggle_fscreen = False
  1318. # Variable to store the status of the code editor
  1319. self.toggle_codeeditor = False
  1320. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1321. self.click_noproject = False
  1322. self.cursor = None
  1323. # Variable to store the GCODE that was edited
  1324. self.gcode_edited = ""
  1325. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1326. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1327. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1328. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1329. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1330. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1331. 'mpf']
  1332. self.svg_list = ['svg']
  1333. self.dxf_list = ['dxf']
  1334. self.prj_list = ['flatprj']
  1335. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1336. # flag for polygons not cleared
  1337. self.poly_not_cleared = False
  1338. # VisPy visuals
  1339. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.vispy_canvas.view.scene, layers=1)
  1340. self.isHovering = False
  1341. self.notHovering = True
  1342. ### Save defaults to factory_defaults.FlatConfig file ###
  1343. ### It's done only once after install #############
  1344. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1345. fac_def_from_file = factory_file.read()
  1346. factory_defaults = json.loads(fac_def_from_file)
  1347. # if the file contain an empty dictionary then save the factory defaults into the file
  1348. if not factory_defaults:
  1349. self.save_factory_defaults(silent=False)
  1350. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1351. initial_lay = 'compact'
  1352. self.on_layout(index=None, lay=initial_lay)
  1353. # Set the combobox in Preferences to the current layout
  1354. idx = self.app.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(
  1355. initial_lay.capitalize()
  1356. )
  1357. self.app.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  1358. factory_file.close()
  1359. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1360. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1361. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1362. # Post-GUI initialization: Experimental attempt
  1363. # to perform unit tests on the GUI.
  1364. # if post_gui is not None:
  1365. # post_gui(self)
  1366. App.log.debug("END of constructor. Releasing control.")
  1367. # accept a project file as command line parameter
  1368. # the path/file_name must be enclosed in quotes if it contain spaces
  1369. for argument in App.args:
  1370. if '.FlatPrj' in argument:
  1371. try:
  1372. project_name = str(argument)
  1373. if project_name == "":
  1374. self.inform.emit(_("Open cancelled."))
  1375. else:
  1376. # self.open_project(project_name)
  1377. run_from_arg = True
  1378. self.worker_task.emit({'fcn': self.open_project,
  1379. 'params': [project_name, run_from_arg]})
  1380. except Exception as e:
  1381. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1382. if '.FlatConfig' in argument:
  1383. try:
  1384. file_name = str(argument)
  1385. if file_name == "":
  1386. self.inform.emit(_("Open Config file failed."))
  1387. else:
  1388. # run_from_arg = True
  1389. # self.worker_task.emit({'fcn': self.open_config_file,
  1390. # 'params': [file_name, run_from_arg]})
  1391. self.open_config_file(file_name, run_from_arg=True)
  1392. except Exception as e:
  1393. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1394. def defaults_read_form(self):
  1395. for option in self.defaults_form_fields:
  1396. try:
  1397. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1398. except:
  1399. pass
  1400. def defaults_write_form(self, factor=None):
  1401. for option in self.defaults:
  1402. self.defaults_write_form_field(option, factor=factor)
  1403. # try:
  1404. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1405. # except KeyError:
  1406. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1407. # # TODO: Rethink this?
  1408. # pass
  1409. def defaults_write_form_field(self, field, factor=None):
  1410. try:
  1411. if factor is None:
  1412. self.defaults_form_fields[field].set_value(self.defaults[field])
  1413. else:
  1414. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  1415. except KeyError:
  1416. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1417. # TODO: Rethink this?
  1418. pass
  1419. except AttributeError:
  1420. log.debug(field)
  1421. def clear_pool(self):
  1422. self.pool.close()
  1423. self.pool = Pool()
  1424. self.pool_recreated.emit(self.pool)
  1425. gc.collect()
  1426. # the order that the tools are installed is important as they can depend on each other install position
  1427. def install_tools(self):
  1428. self.dblsidedtool = DblSidedTool(self)
  1429. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1430. self.measurement_tool = Measurement(self)
  1431. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1432. self.panelize_tool = Panelize(self)
  1433. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1434. self.film_tool = Film(self)
  1435. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1436. self.paste_tool = SolderPaste(self)
  1437. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'), separator=True)
  1438. self.move_tool = ToolMove(self)
  1439. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1440. before=self.ui.menueditorigin)
  1441. self.cutout_tool = CutOut(self)
  1442. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  1443. before=self.measurement_tool.menuAction)
  1444. self.ncclear_tool = NonCopperClear(self)
  1445. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  1446. before=self.measurement_tool.menuAction, separator=True)
  1447. self.paint_tool = ToolPaint(self)
  1448. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1449. before=self.measurement_tool.menuAction, separator=True)
  1450. self.calculator_tool = ToolCalculator(self)
  1451. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1452. self.transform_tool = ToolTransform(self)
  1453. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1454. self.properties_tool = Properties(self)
  1455. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1456. self.image_tool = ToolImage(self)
  1457. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1458. separator=True)
  1459. self.log.debug("Tools are installed.")
  1460. def remove_tools(self):
  1461. for act in self.ui.menutool.actions():
  1462. self.ui.menutool.removeAction(act)
  1463. def init_tools(self):
  1464. log.debug("init_tools()")
  1465. # delete the data currently in the Tools Tab and the Tab itself
  1466. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1467. if widget is not None:
  1468. widget.deleteLater()
  1469. self.ui.notebook.removeTab(2)
  1470. # rebuild the Tools Tab
  1471. self.ui.tool_tab = QtWidgets.QWidget()
  1472. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1473. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1474. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1475. self.ui.tool_scroll_area = VerticalScrollArea()
  1476. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1477. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1478. # first remove all of them
  1479. self.remove_tools()
  1480. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1481. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1482. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1483. # third install all of them
  1484. self.install_tools()
  1485. self.log.debug("Tools are initialized.")
  1486. # def parse_system_fonts(self):
  1487. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1488. # 'params': []})
  1489. def connect_toolbar_signals(self):
  1490. # Toolbar
  1491. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1492. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1493. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1494. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1495. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1496. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1497. self.ui.replot_btn.triggered.connect(self.plot_all)
  1498. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1499. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1500. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1501. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1502. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1503. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1504. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  1505. self.ui.delete_btn.triggered.connect(self.on_delete)
  1506. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1507. # Tools Toolbar Signals
  1508. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1509. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1510. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1511. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1512. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1513. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1514. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1515. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1516. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1517. def object2editor(self):
  1518. """
  1519. Send the current Geometry or Excellon object (if any) into the editor.
  1520. :return: None
  1521. """
  1522. self.report_usage("object2editor()")
  1523. # adjust the visibility of some of the canvas context menu
  1524. self.ui.popmenu_edit.setVisible(False)
  1525. self.ui.popmenu_save.setVisible(True)
  1526. # adjust the status of the menu entries related to the editor
  1527. self.ui.menueditedit.setDisabled(True)
  1528. self.ui.menueditok.setDisabled(False)
  1529. edited_object = self.collection.get_active()
  1530. if isinstance(edited_object, FlatCAMGeometry):
  1531. # for now, if the Geometry is MultiGeo do not allow the editing
  1532. if edited_object.multigeo is True:
  1533. self.inform.emit(_("[WARNING_NOTCL] Editing a MultiGeo Geometry is not possible for the moment."))
  1534. return
  1535. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1536. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1537. self.geo_editor.edit_fcgeometry(edited_object)
  1538. # we set the notebook to hidden
  1539. self.ui.splitter.setSizes([0, 1])
  1540. # set call source to the Editor we go into
  1541. self.call_source = 'geo_editor'
  1542. elif isinstance(edited_object, FlatCAMExcellon):
  1543. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1544. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1545. self.exc_editor.edit_fcexcellon(edited_object)
  1546. # set call source to the Editor we go into
  1547. self.call_source = 'exc_editor'
  1548. else:
  1549. self.inform.emit(_("[WARNING_NOTCL]Select a Geometry or Excellon Object to edit."))
  1550. return
  1551. # make sure that we can't select another object while in Editor Mode:
  1552. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1553. # delete any selection shape that might be active as they are not relevant in Editor
  1554. self.delete_selection_shape()
  1555. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1556. self.ui.plot_tab_area.protectTab(0)
  1557. self.inform.emit(_("[WARNING_NOTCL]Editor is activated ..."))
  1558. self.should_we_save = True
  1559. def editor2object(self):
  1560. """
  1561. Transfers the Geometry or Excellon from the editor to the current object.
  1562. :return: None
  1563. """
  1564. self.report_usage("editor2object()")
  1565. # adjust the status of the menu entries related to the editor
  1566. self.ui.menueditedit.setDisabled(False)
  1567. self.ui.menueditok.setDisabled(True)
  1568. # do not update a geometry or excellon object unless it comes out of an editor
  1569. if self.call_source != 'app':
  1570. # adjust the visibility of some of the canvas context menu
  1571. self.ui.popmenu_edit.setVisible(True)
  1572. self.ui.popmenu_save.setVisible(False)
  1573. edited_obj = self.collection.get_active()
  1574. obj_type = ""
  1575. if isinstance(edited_obj, FlatCAMGeometry):
  1576. obj_type = "Geometry"
  1577. self.geo_editor.update_fcgeometry(edited_obj)
  1578. self.geo_editor.update_options(edited_obj)
  1579. self.geo_editor.deactivate()
  1580. # update the geo object options so it is including the bounding box values
  1581. try:
  1582. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1583. edited_obj.options['xmin'] = xmin
  1584. edited_obj.options['ymin'] = ymin
  1585. edited_obj.options['xmax'] = xmax
  1586. edited_obj.options['ymax'] = ymax
  1587. except AttributeError:
  1588. self.inform.emit(_("[WARNING] Object empty after edit."))
  1589. elif isinstance(edited_obj, FlatCAMExcellon):
  1590. obj_type = "Excellon"
  1591. self.exc_editor.update_fcexcellon(edited_obj)
  1592. self.exc_editor.update_options(edited_obj)
  1593. self.exc_editor.deactivate()
  1594. else:
  1595. self.inform.emit(_("[WARNING_NOTCL]Select a Geometry or Excellon Object to update."))
  1596. return
  1597. # if notebook is hidden we show it
  1598. if self.ui.splitter.sizes()[0] == 0:
  1599. self.ui.splitter.setSizes([1, 1])
  1600. # restore the call_source to app
  1601. self.call_source = 'app'
  1602. edited_obj.plot()
  1603. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1604. self.ui.plot_tab_area.protectTab(0)
  1605. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1606. # reset the Object UI to original settings
  1607. # edited_obj.set_ui(edited_obj.ui_type())
  1608. # edited_obj.build_ui()
  1609. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1610. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1611. def get_last_folder(self):
  1612. return self.defaults["global_last_folder"]
  1613. def get_last_save_folder(self):
  1614. loc = self.defaults["global_last_save_folder"]
  1615. if loc is None:
  1616. loc = self.defaults["global_last_folder"]
  1617. if loc is None:
  1618. loc = os.path.dirname(__file__)
  1619. return loc
  1620. def report_usage(self, resource):
  1621. """
  1622. Increments usage counter for the given resource
  1623. in self.defaults['global_stats'].
  1624. :param resource: Name of the resource.
  1625. :return: None
  1626. """
  1627. if resource in self.defaults['global_stats']:
  1628. self.defaults['global_stats'][resource] += 1
  1629. else:
  1630. self.defaults['global_stats'][resource] = 1
  1631. def init_tcl(self):
  1632. if hasattr(self,'tcl'):
  1633. # self.tcl = None
  1634. # TODO we need to clean non default variables and procedures here
  1635. # new object cannot be used here as it will not remember values created for next passes,
  1636. # because tcl was execudted in old instance of TCL
  1637. pass
  1638. else:
  1639. self.tcl = tk.Tcl()
  1640. self.setup_shell()
  1641. self.log.debug("TCL Shell has been initialized.")
  1642. # TODO: This shouldn't be here.
  1643. class TclErrorException(Exception):
  1644. """
  1645. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1646. """
  1647. pass
  1648. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1649. """
  1650. Shows a message on the FlatCAM Shell
  1651. :param msg: Message to display.
  1652. :param show: Opens the shell.
  1653. :param error: Shows the message as an error.
  1654. :return: None
  1655. """
  1656. if show:
  1657. self.ui.shell_dock.show()
  1658. try:
  1659. if error:
  1660. self.shell.append_error(msg + "\n")
  1661. elif warning:
  1662. self.shell.append_warning(msg + "\n")
  1663. elif success:
  1664. self.shell.append_success(msg + "\n")
  1665. elif selected:
  1666. self.shell.append_selected(msg + "\n")
  1667. else:
  1668. self.shell.append_output(msg + "\n")
  1669. except AttributeError:
  1670. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1671. def raise_tcl_unknown_error(self, unknownException):
  1672. """
  1673. Raise exception if is different type than TclErrorException
  1674. this is here mainly to show unknown errors inside TCL shell console.
  1675. :param unknownException:
  1676. :return:
  1677. """
  1678. if not isinstance(unknownException, self.TclErrorException):
  1679. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1680. else:
  1681. raise unknownException
  1682. def display_tcl_error(self, error, error_info=None):
  1683. """
  1684. escape bracket [ with \ otherwise there is error
  1685. "ERROR: missing close-bracket" instead of real error
  1686. :param error: it may be text or exception
  1687. :return: None
  1688. """
  1689. if isinstance(error, Exception):
  1690. exc_type, exc_value, exc_traceback = error_info
  1691. if not isinstance(error, self.TclErrorException):
  1692. show_trace = 1
  1693. else:
  1694. show_trace = int(self.defaults['global_verbose_error_level'])
  1695. if show_trace > 0:
  1696. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1697. trc_formated = []
  1698. for a in reversed(trc):
  1699. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1700. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1701. exc_type,
  1702. "\n".join(trc_formated))
  1703. else:
  1704. text = "%s" % error
  1705. else:
  1706. text = error
  1707. text = text.replace('[', '\\[').replace('"', '\\"')
  1708. self.tcl.eval('return -code error "%s"' % text)
  1709. def raise_tcl_error(self, text):
  1710. """
  1711. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1712. :param text: text of error
  1713. :return: raise exception
  1714. """
  1715. self.display_tcl_error(text)
  1716. raise self.TclErrorException(text)
  1717. def exec_command(self, text):
  1718. """
  1719. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1720. Also handles execution in separated threads
  1721. :param text:
  1722. :return: output if there was any
  1723. """
  1724. self.report_usage('exec_command')
  1725. result = self.exec_command_test(text, False)
  1726. #MS: added this method call so the geometry is updated once the TCL
  1727. #command is executed
  1728. self.plot_all()
  1729. return result
  1730. def exec_command_test(self, text, reraise=True):
  1731. """
  1732. Same as exec_command(...) with additional control over exceptions.
  1733. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1734. :param text: Input command
  1735. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1736. :return: Output from the command
  1737. """
  1738. text = str(text)
  1739. try:
  1740. self.shell.open_proccessing() # Disables input box.
  1741. result = self.tcl.eval(str(text))
  1742. if result != 'None':
  1743. self.shell.append_output(result + '\n')
  1744. except tk.TclError as e:
  1745. # This will display more precise answer if something in TCL shell fails
  1746. result = self.tcl.eval("set errorInfo")
  1747. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1748. self.shell.append_error('ERROR: ' + result + '\n')
  1749. # Show error in console and just return or in test raise exception
  1750. if reraise:
  1751. raise e
  1752. finally:
  1753. self.shell.close_proccessing()
  1754. pass
  1755. return result
  1756. # """
  1757. # Code below is unsused. Saved for later.
  1758. # """
  1759. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1760. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1761. # self.log.debug(parts)
  1762. # try:
  1763. # if parts[0] not in commands:
  1764. # self.shell.append_error("Unknown command\n")
  1765. # return
  1766. #
  1767. # #import inspect
  1768. # #inspect.getargspec(someMethod)
  1769. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1770. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1771. # self.shell.append_error(
  1772. # "Command %s takes %d arguments. %d given.\n" %
  1773. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1774. # )
  1775. # return
  1776. #
  1777. # cmdfcn = commands[parts[0]]["fcn"]
  1778. # cmdconv = commands[parts[0]]["converters"]
  1779. # if len(parts) - 1 > 0:
  1780. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1781. # else:
  1782. # retval = cmdfcn()
  1783. # retfcn = commands[parts[0]]["retfcn"]
  1784. # if retval and retfcn(retval):
  1785. # self.shell.append_output(retfcn(retval) + "\n")
  1786. #
  1787. # except Exception as e:
  1788. # #self.shell.append_error(''.join(traceback.format_exc()))
  1789. # #self.shell.append_error("?\n")
  1790. # self.shell.append_error(str(e) + "\n")
  1791. def info(self, msg):
  1792. """
  1793. Informs the user. Normally on the status bar, optionally
  1794. also on the shell.
  1795. :param msg: Text to write.
  1796. :return: None
  1797. """
  1798. # Type of message in brackets at the begining of the message.
  1799. match = re.search("\[([^\]]+)\](.*)", msg)
  1800. if match:
  1801. level = match.group(1)
  1802. msg_ = match.group(2)
  1803. self.ui.fcinfo.set_status(str(msg_), level=level)
  1804. if level.lower() == "error":
  1805. self.shell_message(msg, error=True, show=True)
  1806. elif level.lower() == "warning":
  1807. self.shell_message(msg, warning=True, show=True)
  1808. elif level.lower() == "error_notcl":
  1809. self.shell_message(msg, error=True, show=False)
  1810. elif level.lower() == "warning_notcl":
  1811. self.shell_message(msg, warning=True, show=False)
  1812. elif level.lower() == "success":
  1813. self.shell_message(msg, success=True, show=False)
  1814. elif level.lower() == "selected":
  1815. self.shell_message(msg, selected=True, show=False)
  1816. else:
  1817. self.shell_message(msg, show=False)
  1818. else:
  1819. self.ui.fcinfo.set_status(str(msg), level="info")
  1820. # make sure that if the message is to clear the infobar with a space
  1821. # is not printed over and over on the shell
  1822. if msg != '':
  1823. self.shell_message(msg)
  1824. def restore_toolbar_view(self):
  1825. tb = self.defaults["global_toolbar_view"]
  1826. if tb & 1:
  1827. self.ui.toolbarfile.setVisible(True)
  1828. else:
  1829. self.ui.toolbarfile.setVisible(False)
  1830. if tb & 2:
  1831. self.ui.toolbargeo.setVisible(True)
  1832. else:
  1833. self.ui.toolbargeo.setVisible(False)
  1834. if tb & 4:
  1835. self.ui.toolbarview.setVisible(True)
  1836. else:
  1837. self.ui.toolbarview.setVisible(False)
  1838. if tb & 8:
  1839. self.ui.toolbartools.setVisible(True)
  1840. else:
  1841. self.ui.toolbartools.setVisible(False)
  1842. if tb & 16:
  1843. self.ui.exc_edit_toolbar.setVisible(True)
  1844. else:
  1845. self.ui.exc_edit_toolbar.setVisible(False)
  1846. if tb & 32:
  1847. self.ui.geo_edit_toolbar.setVisible(True)
  1848. else:
  1849. self.ui.geo_edit_toolbar.setVisible(False)
  1850. if tb & 64:
  1851. self.ui.snap_toolbar.setVisible(True)
  1852. else:
  1853. self.ui.snap_toolbar.setVisible(False)
  1854. if tb & 128:
  1855. self.ui.toolbarshell.setVisible(True)
  1856. else:
  1857. self.ui.toolbarshell.setVisible(False)
  1858. def load_defaults(self, filename):
  1859. """
  1860. Loads the aplication's default settings from current_defaults.FlatConfig into
  1861. ``self.defaults``.
  1862. :return: None
  1863. """
  1864. try:
  1865. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1866. options = f.read()
  1867. f.close()
  1868. except IOError:
  1869. self.log.error("Could not load defaults file.")
  1870. self.inform.emit(_("[ERROR] Could not load defaults file."))
  1871. # in case the defaults file can't be loaded, show all toolbars
  1872. self.defaults["global_toolbar_view"] = 255
  1873. return
  1874. try:
  1875. defaults = json.loads(options)
  1876. except:
  1877. # in case the defaults file can't be loaded, show all toolbars
  1878. self.defaults["global_toolbar_view"] = 255
  1879. e = sys.exc_info()[0]
  1880. App.log.error(str(e))
  1881. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  1882. return
  1883. self.defaults.update(defaults)
  1884. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1885. # restore the toolbar view
  1886. self.restore_toolbar_view()
  1887. def on_import_preferences(self):
  1888. """
  1889. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1890. ``self.defaults``.
  1891. :return: None
  1892. """
  1893. self.report_usage("on_import_preferences")
  1894. App.log.debug("on_import_preferences()")
  1895. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1896. try:
  1897. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  1898. directory=self.data_path, filter=filter)
  1899. except TypeError:
  1900. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"), filter=filter)
  1901. filename = str(filename)
  1902. if filename == "":
  1903. self.inform.emit(_("[WARNING_NOTCL]FlatCAM preferences import cancelled."))
  1904. else:
  1905. try:
  1906. f = open(filename)
  1907. options = f.read()
  1908. f.close()
  1909. except IOError:
  1910. self.log.error("Could not load defaults file.")
  1911. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  1912. return
  1913. try:
  1914. defaults_from_file = json.loads(options)
  1915. except:
  1916. e = sys.exc_info()[0]
  1917. App.log.error(str(e))
  1918. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  1919. return
  1920. self.defaults.update(defaults_from_file)
  1921. self.inform.emit(_("[success]Imported Defaults from %s") %filename)
  1922. def on_export_preferences(self):
  1923. self.report_usage("on_export_preferences")
  1924. App.log.debug("on_export_preferences()")
  1925. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1926. try:
  1927. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  1928. caption=_("Export FlatCAM Preferences"),
  1929. directory=self.data_path + '/preferences_' + self.date.replace('-', ''), filter=filter
  1930. )
  1931. except TypeError:
  1932. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"), filter=filter)
  1933. filename = str(filename)
  1934. defaults_from_file = {}
  1935. if filename == "":
  1936. self.inform.emit(_("[WARNING_NOTCL]FlatCAM preferences export cancelled."))
  1937. return
  1938. else:
  1939. try:
  1940. f = open(filename, 'w')
  1941. defaults_file_content = f.read()
  1942. f.close()
  1943. except IOError:
  1944. App.log.debug('Creating a new preferences file ...')
  1945. f = open(filename, 'w')
  1946. json.dump({}, f)
  1947. f.close()
  1948. except:
  1949. e = sys.exc_info()[0]
  1950. App.log.error("Could not load defaults file.")
  1951. App.log.error(str(e))
  1952. self.inform.emit(_("[ERROR_NOTCL]Could not load defaults file."))
  1953. return
  1954. try:
  1955. defaults_from_file = json.loads(defaults_file_content)
  1956. except:
  1957. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1958. # Update options
  1959. self.defaults_read_form()
  1960. defaults_from_file.update(self.defaults)
  1961. self.propagate_defaults(silent=True)
  1962. # Save update options
  1963. try:
  1964. f = open(filename, "w")
  1965. json.dump(defaults_from_file, f)
  1966. f.close()
  1967. except:
  1968. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  1969. return
  1970. self.file_saved.emit("preferences", filename)
  1971. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1972. def on_preferences_open_folder(self):
  1973. self.report_usage("on_preferences_open_folder()")
  1974. if sys.platform == 'win32':
  1975. subprocess.Popen('explorer %s' % self.data_path)
  1976. elif sys.platform == 'darwin':
  1977. os.system('open "%s"' % self.data_path)
  1978. else:
  1979. subprocess.Popen(['xdg-open', self.data_path])
  1980. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1981. def save_geometry(self, x, y, width, height, notebook_width):
  1982. self.defaults["global_def_win_x"] = x
  1983. self.defaults["global_def_win_y"] = y
  1984. self.defaults["global_def_win_w"] = width
  1985. self.defaults["global_def_win_h"] = height
  1986. self.defaults["def_notebook_width"] = notebook_width
  1987. self.save_defaults()
  1988. def message_dialog(self, title, message, kind="info"):
  1989. icon = {"info": QtWidgets.QMessageBox.Information,
  1990. "warning": QtWidgets.QMessageBox.Warning,
  1991. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1992. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1993. dlg.setText(message)
  1994. dlg.exec_()
  1995. def register_recent(self, kind, filename):
  1996. self.log.debug("register_recent()")
  1997. self.log.debug(" %s" % kind)
  1998. self.log.debug(" %s" % filename)
  1999. record = {'kind': str(kind), 'filename': str(filename)}
  2000. if record in self.recent:
  2001. return
  2002. self.recent.insert(0, record)
  2003. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2004. self.recent.pop()
  2005. try:
  2006. f = open(self.data_path + '/recent.json', 'w')
  2007. except IOError:
  2008. App.log.error("Failed to open recent items file for writing.")
  2009. self.inform.emit(_('[ERROR_NOTCL]Failed to open recent files file for writing.'))
  2010. return
  2011. #try:
  2012. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2013. # except:
  2014. # App.log.error("Failed to write to recent items file.")
  2015. # self.inform.emit('ERROR: Failed to write to recent items file.')
  2016. # f.close()
  2017. f.close()
  2018. # Re-buid the recent items menu
  2019. self.setup_recent_items()
  2020. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2021. """
  2022. Creates a new specalized FlatCAMObj and attaches it to the application,
  2023. this is, updates the GUI accordingly, any other records and plots it.
  2024. This method is thread-safe.
  2025. Notes:
  2026. * If the name is in use, the self.collection will modify it
  2027. when appending it to the collection. There is no need to handle
  2028. name conflicts here.
  2029. :param kind: The kind of object to create. One of 'gerber',
  2030. 'excellon', 'cncjob' and 'geometry'.
  2031. :type kind: str
  2032. :param name: Name for the object.
  2033. :type name: str
  2034. :param initialize: Function to run after creation of the object
  2035. but before it is attached to the application. The function is
  2036. called with 2 parameters: the new object and the App instance.
  2037. :type initialize: function
  2038. :return: None
  2039. :rtype: None
  2040. """
  2041. App.log.debug("new_object()")
  2042. obj_plot = plot
  2043. obj_autoselected = autoselected
  2044. t0 = time.time() # Debug
  2045. ## Create object
  2046. classdict = {
  2047. "gerber": FlatCAMGerber,
  2048. "excellon": FlatCAMExcellon,
  2049. "cncjob": FlatCAMCNCjob,
  2050. "geometry": FlatCAMGeometry
  2051. }
  2052. App.log.debug("Calling object constructor...")
  2053. obj = classdict[kind](name)
  2054. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2055. # Set options from "Project options" form
  2056. self.options_read_form()
  2057. # IMPORTANT
  2058. # The key names in defaults and options dictionary's are not random:
  2059. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2060. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2061. # the options from project options form into the self.options. After that, below, depending on the type of
  2062. # object that is created, it will strip the name of the object and the underline (if the original key was
  2063. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2064. # "toolchange"
  2065. for option in self.options:
  2066. if option.find(kind + "_") == 0:
  2067. oname = option[len(kind) + 1:]
  2068. obj.options[oname] = self.options[option]
  2069. obj.isHovering = False
  2070. obj.notHovering = True
  2071. # Initialize as per user request
  2072. # User must take care to implement initialize
  2073. # in a thread-safe way as is is likely that we
  2074. # have been invoked in a separate thread.
  2075. t1 = time.time()
  2076. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2077. try:
  2078. return_value = initialize(obj, self)
  2079. except Exception as e:
  2080. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2081. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2082. msg += traceback.format_exc()
  2083. self.inform.emit(msg)
  2084. # if str(e) == "Empty Geometry":
  2085. # self.inform.emit("[ERROR_NOTCL] )
  2086. # else:
  2087. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2088. return "fail"
  2089. t2 = time.time()
  2090. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2091. if return_value == 'fail':
  2092. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2093. return "fail"
  2094. # Check units and convert if necessary
  2095. # This condition CAN be true because initialize() can change obj.units
  2096. if self.options["units"].upper() != obj.units.upper():
  2097. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2098. obj.convert_units(self.options["units"])
  2099. t3 = time.time()
  2100. self.log.debug("%f seconds converting units." % (t3 - t2))
  2101. # Create the bounding box for the object and then add the results to the obj.options
  2102. try:
  2103. xmin, ymin, xmax, ymax = obj.bounds()
  2104. obj.options['xmin'] = xmin
  2105. obj.options['ymin'] = ymin
  2106. obj.options['xmax'] = xmax
  2107. obj.options['ymax'] = ymax
  2108. except:
  2109. log.warning("The object has no bounds properties.")
  2110. # don't plot objects with no bounds, there is nothing to plot
  2111. self.plot = False
  2112. pass
  2113. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2114. # Move the object to the main thread and let the app know that it is available.
  2115. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  2116. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2117. return obj
  2118. def new_excellon_object(self):
  2119. self.report_usage("new_excellon_object()")
  2120. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  2121. def new_geometry_object(self):
  2122. self.report_usage("new_geometry_object()")
  2123. def initialize(obj, self):
  2124. obj.multitool = False
  2125. self.new_object('geometry', 'new_g', initialize, plot=False)
  2126. def on_object_created(self, obj, plot, autoselect):
  2127. """
  2128. Event callback for object creation.
  2129. :param obj: The newly created FlatCAM object.
  2130. :return: None
  2131. """
  2132. t0 = time.time() # DEBUG
  2133. self.log.debug("on_object_created()")
  2134. # The Collection might change the name if there is a collision
  2135. self.collection.append(obj)
  2136. # after adding the object to the collection always update the list of objects that are in the collection
  2137. self.all_objects_list = self.collection.get_list()
  2138. # self.inform.emit('[selected] %s created & selected: %s' %
  2139. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2140. if obj.kind == 'gerber':
  2141. self.inform.emit(_('[selected]{kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2142. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2143. elif obj.kind == 'excellon':
  2144. self.inform.emit(_('[selected]{kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2145. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2146. elif obj.kind == 'cncjob':
  2147. self.inform.emit(_('[selected]{kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2148. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2149. elif obj.kind == 'geometry':
  2150. self.inform.emit(_('[selected]{kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2151. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2152. # update the SHELL auto-completer model with the name of the new object
  2153. self.myKeywords.append(obj.options['name'])
  2154. self.shell._edit.set_model_data(self.myKeywords)
  2155. if autoselect:
  2156. # select the just opened object but deselect the previous ones
  2157. self.collection.set_all_inactive()
  2158. self.collection.set_active(obj.options["name"])
  2159. # here it is done the object plotting
  2160. def worker_task(obj):
  2161. with self.proc_container.new("Plotting"):
  2162. if isinstance(obj, FlatCAMCNCjob):
  2163. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2164. else:
  2165. obj.plot()
  2166. t1 = time.time() # DEBUG
  2167. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2168. self.object_plotted.emit(obj)
  2169. # Send to worker
  2170. # self.worker.add_task(worker_task, [self])
  2171. if plot is True:
  2172. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2173. def on_object_changed(self, obj):
  2174. # update the bounding box data from obj.options
  2175. xmin, ymin, xmax, ymax = obj.bounds()
  2176. obj.options['xmin'] = xmin
  2177. obj.options['ymin'] = ymin
  2178. obj.options['xmax'] = xmax
  2179. obj.options['ymax'] = ymax
  2180. log.debug("Object changed, updating the bounding box data on self.options")
  2181. # delete the old selection shape
  2182. self.delete_selection_shape()
  2183. self.should_we_save = True
  2184. def on_object_plotted(self, obj):
  2185. self.on_zoom_fit(None)
  2186. def options_read_form(self):
  2187. for option in self.options_form_fields:
  2188. self.options[option] = self.options_form_fields[option].get_value()
  2189. def options_write_form(self):
  2190. for option in self.options:
  2191. self.options_write_form_field(option)
  2192. def options_write_form_field(self, field):
  2193. try:
  2194. self.options_form_fields[field].set_value(self.options[field])
  2195. except KeyError:
  2196. # Changed from error to debug. This allows to have data stored
  2197. # which is not user-editable.
  2198. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2199. pass
  2200. def on_about(self):
  2201. """
  2202. Displays the "about" dialog.
  2203. :return: None
  2204. """
  2205. self.report_usage("on_about")
  2206. version = self.version
  2207. version_date = self.version_date
  2208. beta = self.beta
  2209. class AboutDialog(QtWidgets.QDialog):
  2210. def __init__(self, parent=None):
  2211. QtWidgets.QDialog.__init__(self, parent)
  2212. # Icon and title
  2213. self.setWindowIcon(parent.app_icon)
  2214. self.setWindowTitle("FlatCAM")
  2215. layout1 = QtWidgets.QVBoxLayout()
  2216. self.setLayout(layout1)
  2217. layout2 = QtWidgets.QHBoxLayout()
  2218. layout1.addLayout(layout2)
  2219. logo = QtWidgets.QLabel()
  2220. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2221. layout2.addWidget(logo, stretch=0)
  2222. title = QtWidgets.QLabel(
  2223. _(
  2224. "<font size=8><B>FlatCAM</B></font><BR>"
  2225. "Version {version} {beta} ({date}) - {arch} <BR>"
  2226. "<BR>"
  2227. "2D Computer-Aided Printed Circuit Board<BR>"
  2228. "Manufacturing.<BR>"
  2229. "<BR>"
  2230. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2231. "<BR>"
  2232. "<B> Main Contributors:</B><BR>"
  2233. "Denis Hayrullin<BR>"
  2234. "Kamil Sopko<BR>"
  2235. "Marius Stanciu<BR>"
  2236. "Matthieu Berthomé<BR>"
  2237. "and many others found "
  2238. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2239. "<BR>"
  2240. "Development is done "
  2241. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2242. "DOWNLOAD area "
  2243. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2244. ""
  2245. ).format(version=version,
  2246. beta=('BETA' if beta else ''),
  2247. date=version_date,
  2248. arch=platform.architecture()[0])
  2249. )
  2250. title.setOpenExternalLinks(True)
  2251. layout2.addWidget(title, stretch=1)
  2252. layout3 = QtWidgets.QHBoxLayout()
  2253. layout1.addLayout(layout3)
  2254. layout3.addStretch()
  2255. okbtn = QtWidgets.QPushButton("Close")
  2256. layout3.addWidget(okbtn)
  2257. okbtn.clicked.connect(self.accept)
  2258. AboutDialog(self.ui).exec_()
  2259. def on_file_savedefaults(self):
  2260. """
  2261. Callback for menu item File->Save Defaults. Saves application default options
  2262. ``self.defaults`` to current_defaults.FlatConfig.
  2263. :return: None
  2264. """
  2265. self.save_defaults()
  2266. def on_app_exit(self):
  2267. self.report_usage("on_app_exit()")
  2268. if self.collection.get_list():
  2269. msgbox = QtWidgets.QMessageBox()
  2270. # msgbox.setText("<B>Save changes ...</B>")
  2271. msgbox.setText("There are files/objects opened in FlatCAM. "
  2272. "\n"
  2273. "Do you want to Save the project?")
  2274. msgbox.setWindowTitle("Save changes")
  2275. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2276. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2277. QtWidgets.QMessageBox.Cancel)
  2278. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2279. response = msgbox.exec_()
  2280. if response == QtWidgets.QMessageBox.Yes:
  2281. self.on_file_saveprojectas(thread=False)
  2282. elif response == QtWidgets.QMessageBox.Cancel:
  2283. return
  2284. self.save_defaults()
  2285. else:
  2286. self.save_defaults()
  2287. log.debug("Application defaults saved ... Exit event.")
  2288. QtWidgets.qApp.quit()
  2289. def save_defaults(self, silent=False):
  2290. """
  2291. Saves application default options
  2292. ``self.defaults`` to current_defaults.FlatConfig.
  2293. :return: None
  2294. """
  2295. self.report_usage("save_defaults")
  2296. # Read options from file
  2297. try:
  2298. f = open(self.data_path + "/current_defaults.FlatConfig")
  2299. defaults_file_content = f.read()
  2300. f.close()
  2301. except:
  2302. e = sys.exc_info()[0]
  2303. App.log.error("Could not load defaults file.")
  2304. App.log.error(str(e))
  2305. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2306. return
  2307. try:
  2308. defaults = json.loads(defaults_file_content)
  2309. except:
  2310. e = sys.exc_info()[0]
  2311. App.log.error("Failed to parse defaults file.")
  2312. App.log.error(str(e))
  2313. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2314. return
  2315. # Update options
  2316. self.defaults_read_form()
  2317. defaults.update(self.defaults)
  2318. self.propagate_defaults(silent=True)
  2319. # Save update options
  2320. try:
  2321. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2322. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2323. f.close()
  2324. except:
  2325. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2326. return
  2327. # Save the toolbar view
  2328. tb_status = 0
  2329. if self.ui.toolbarfile.isVisible():
  2330. tb_status += 1
  2331. if self.ui.toolbargeo.isVisible():
  2332. tb_status += 2
  2333. if self.ui.toolbarview.isVisible():
  2334. tb_status += 4
  2335. if self.ui.toolbartools.isVisible():
  2336. tb_status += 8
  2337. if self.ui.exc_edit_toolbar.isVisible():
  2338. tb_status += 16
  2339. if self.ui.geo_edit_toolbar.isVisible():
  2340. tb_status += 32
  2341. if self.ui.snap_toolbar.isVisible():
  2342. tb_status += 64
  2343. if self.ui.toolbarshell.isVisible():
  2344. tb_status += 128
  2345. self.defaults["global_toolbar_view"] = tb_status
  2346. if not silent:
  2347. self.inform.emit(_("[success]Defaults saved."))
  2348. def save_factory_defaults(self, silent=False):
  2349. """
  2350. Saves application factory default options
  2351. ``self.defaults`` to factory_defaults.FlatConfig.
  2352. It's a one time job done just after the first install.
  2353. :return: None
  2354. """
  2355. self.report_usage("save_factory_defaults")
  2356. # Read options from file
  2357. try:
  2358. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2359. factory_defaults_file_content = f_f_def.read()
  2360. f_f_def.close()
  2361. except:
  2362. e = sys.exc_info()[0]
  2363. App.log.error("Could not load factory defaults file.")
  2364. App.log.error(str(e))
  2365. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2366. return
  2367. try:
  2368. factory_defaults = json.loads(factory_defaults_file_content)
  2369. except:
  2370. e = sys.exc_info()[0]
  2371. App.log.error("Failed to parse factory defaults file.")
  2372. App.log.error(str(e))
  2373. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2374. return
  2375. # Update options
  2376. self.defaults_read_form()
  2377. factory_defaults.update(self.defaults)
  2378. self.propagate_defaults(silent=True)
  2379. # Save update options
  2380. try:
  2381. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2382. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2383. f_f_def_s.close()
  2384. except:
  2385. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2386. return
  2387. if silent is False:
  2388. self.inform.emit(_("Factory defaults saved."))
  2389. def final_save(self):
  2390. if self.should_we_save and self.collection.get_list():
  2391. msgbox = QtWidgets.QMessageBox()
  2392. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2393. "\n"
  2394. "Do you want to Save the project?"))
  2395. msgbox.setWindowTitle(_("Save changes"))
  2396. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2397. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2398. QtWidgets.QMessageBox.Cancel)
  2399. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2400. response = msgbox.exec_()
  2401. if response == QtWidgets.QMessageBox.Yes:
  2402. self.on_file_saveprojectas(thread=False)
  2403. elif response == QtWidgets.QMessageBox.Cancel:
  2404. self.should_we_quit = False
  2405. return
  2406. self.save_defaults()
  2407. log.debug("App.final_save() --> App Defaults saved.")
  2408. # save toolbar state to file
  2409. settings = QSettings("Open Source", "FlatCAM")
  2410. settings.setValue('saved_gui_state', self.ui.saveState())
  2411. settings.setValue('maximized_gui', self.ui.isMaximized())
  2412. # This will write the setting to the platform specific storage.
  2413. del settings
  2414. log.debug("App.final_save() --> App UI state saved.")
  2415. QtWidgets.qApp.quit()
  2416. def on_toggle_shell(self):
  2417. """
  2418. toggle shell if is visible close it if closed open it
  2419. :return:
  2420. """
  2421. self.report_usage("on_toggle_shell()")
  2422. if self.ui.shell_dock.isVisible():
  2423. self.ui.shell_dock.hide()
  2424. else:
  2425. self.ui.shell_dock.show()
  2426. def on_edit_join(self, name=None):
  2427. """
  2428. Callback for Edit->Join. Joins the selected geometry objects into
  2429. a new one.
  2430. :return: None
  2431. """
  2432. self.report_usage("on_edit_join()")
  2433. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2434. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2435. tooldias = []
  2436. geo_type_list = []
  2437. objs = self.collection.get_selected()
  2438. for obj in objs:
  2439. geo_type_list.append(obj.multigeo)
  2440. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2441. if len(set(geo_type_list)) != 1:
  2442. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2443. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2444. "convert from one to another and retry joining \n"
  2445. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2446. "the result may not be what was expected. \n"
  2447. "Check the generated GCODE."))
  2448. return
  2449. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2450. if True in geo_type_list:
  2451. def initialize(obj, app):
  2452. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2453. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2454. for v in obj.tools.values():
  2455. v['data']['name'] = obj_name_multi
  2456. self.new_object("geometry", obj_name_multi, initialize)
  2457. else:
  2458. def initialize(obj, app):
  2459. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2460. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2461. for v in obj.tools.values():
  2462. v['data']['name'] = obj_name_single
  2463. self.new_object("geometry", obj_name_single, initialize)
  2464. self.should_we_save = True
  2465. def on_edit_join_exc(self):
  2466. """
  2467. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2468. a new one.
  2469. :return: None
  2470. """
  2471. self.report_usage("on_edit_join_exc()")
  2472. objs = self.collection.get_selected()
  2473. for obj in objs:
  2474. if not isinstance(obj, FlatCAMExcellon):
  2475. self.inform.emit(_("[ERROR_NOTCL]Failed. Excellon joining works only on Excellon objects."))
  2476. return
  2477. def initialize(obj, app):
  2478. FlatCAMExcellon.merge(objs, obj)
  2479. self.new_object("excellon", 'Combo_Excellon', initialize)
  2480. self.should_we_save = True
  2481. def on_edit_join_grb(self):
  2482. """
  2483. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2484. a new one.
  2485. :return: None
  2486. """
  2487. self.report_usage("on_edit_join_grb()")
  2488. objs = self.collection.get_selected()
  2489. for obj in objs:
  2490. if not isinstance(obj, FlatCAMGerber):
  2491. self.inform.emit(_("[ERROR_NOTCL]Failed. Gerber joining works only on Gerber objects."))
  2492. return
  2493. def initialize(obj, app):
  2494. FlatCAMGerber.merge(objs, obj)
  2495. self.new_object("gerber", 'Combo_Gerber', initialize)
  2496. self.should_we_save = True
  2497. def on_convert_singlegeo_to_multigeo(self):
  2498. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2499. obj = self.collection.get_active()
  2500. if obj is None:
  2501. self.inform.emit(_("[ERROR_NOTCL]Failed. Select a Geometry Object and try again."))
  2502. return
  2503. if not isinstance(obj, FlatCAMGeometry):
  2504. self.inform.emit(_("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s") % type(obj))
  2505. return
  2506. obj.multigeo = True
  2507. for tooluid, dict_value in obj.tools.items():
  2508. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2509. if not isinstance(obj.solid_geometry, list):
  2510. obj.solid_geometry = [obj.solid_geometry]
  2511. obj.solid_geometry[:] = []
  2512. obj.plot()
  2513. self.should_we_save = True
  2514. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2515. def on_convert_multigeo_to_singlegeo(self):
  2516. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2517. obj = self.collection.get_active()
  2518. if obj is None:
  2519. self.inform.emit(_("[ERROR_NOTCL]Failed. Select a Geometry Object and try again."))
  2520. return
  2521. if not isinstance(obj, FlatCAMGeometry):
  2522. self.inform.emit(_("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s") % type(obj))
  2523. return
  2524. obj.multigeo = False
  2525. total_solid_geometry = []
  2526. for tooluid, dict_value in obj.tools.items():
  2527. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2528. # clear the original geometry
  2529. dict_value['solid_geometry'][:] = []
  2530. obj.solid_geometry = deepcopy(total_solid_geometry)
  2531. obj.plot()
  2532. self.should_we_save = True
  2533. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2534. def on_options_dict_change(self, field):
  2535. self.options_write_form_field(field)
  2536. if field == "units":
  2537. self.set_screen_units(self.options['units'])
  2538. def on_defaults_dict_change(self, field):
  2539. self.defaults_write_form_field(field)
  2540. if field == "units":
  2541. self.set_screen_units(self.defaults['units'])
  2542. def set_screen_units(self, units):
  2543. self.ui.units_label.setText("[" + self.defaults["units"].lower() + "]")
  2544. def on_toggle_units(self):
  2545. """
  2546. Callback for the Units radio-button change in the Options tab.
  2547. Changes the application's default units or the current project's units.
  2548. If changing the project's units, the change propagates to all of
  2549. the objects in the project.
  2550. :return: None
  2551. """
  2552. self.report_usage("on_toggle_units")
  2553. if self.toggle_units_ignore:
  2554. return
  2555. # If option is the same, then ignore
  2556. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  2557. self.defaults["units"].upper():
  2558. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  2559. return
  2560. # Options to scale
  2561. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  2562. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  2563. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2564. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  2565. "excellon_z_pdepth",
  2566. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  2567. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  2568. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  2569. "geometry_feedrate_probe",
  2570. 'cncjob_tooldia',
  2571. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  2572. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  2573. "tools_2sided_drilldia", "tools_film_boundary",
  2574. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2575. "tools_panelize_constrainx", "tools_panelize_constrainy",
  2576. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  2577. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  2578. "tools_transform_offset_y",
  2579. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  2580. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  2581. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  2582. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  2583. 'global_gridx', 'global_gridy', 'global_snap_max']
  2584. def scale_options(sfactor):
  2585. for dim in dimensions:
  2586. if dim == 'excellon_toolchangexy':
  2587. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2588. coords_xy[0] *= sfactor
  2589. coords_xy[1] *= sfactor
  2590. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2591. elif dim == 'geometry_toolchangexy':
  2592. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2593. coords_xy[0] *= sfactor
  2594. coords_xy[1] *= sfactor
  2595. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2596. elif dim == 'tools_ncctools':
  2597. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2598. ncctols[0] *= sfactor
  2599. ncctols[1] *= sfactor
  2600. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  2601. elif dim == 'tools_solderpaste_tools':
  2602. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2603. sp_tools[0] *= sfactor
  2604. sp_tools[1] *= sfactor
  2605. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  2606. elif dim == 'tools_solderpaste_xy_toolchange':
  2607. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2608. sp_coords[0] *= sfactor
  2609. sp_coords[1] *= sfactor
  2610. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  2611. else:
  2612. try:
  2613. self.options[dim] = float(self.options[dim]) * sfactor
  2614. except Exception as e:
  2615. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  2616. def scale_defaults(sfactor):
  2617. for dim in dimensions:
  2618. if dim == 'excellon_toolchangexy':
  2619. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2620. coords_xy[0] *= sfactor
  2621. coords_xy[1] *= sfactor
  2622. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2623. elif dim == 'geometry_toolchangexy':
  2624. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2625. coords_xy[0] *= sfactor
  2626. coords_xy[1] *= sfactor
  2627. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2628. elif dim == 'tools_ncctools':
  2629. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2630. ncctols[0] *= sfactor
  2631. ncctols[1] *= sfactor
  2632. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  2633. elif dim == 'tools_solderpaste_tools':
  2634. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2635. sp_tools[0] *= sfactor
  2636. sp_tools[1] *= sfactor
  2637. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  2638. elif dim == 'tools_solderpaste_xy_toolchange':
  2639. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2640. sp_coords[0] *= sfactor
  2641. sp_coords[1] *= sfactor
  2642. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  2643. else:
  2644. try:
  2645. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  2646. except Exception as e:
  2647. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  2648. # The scaling factor depending on choice of units.
  2649. factor = 1/25.4
  2650. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2651. factor = 25.4
  2652. # Changing project units. Warn user.
  2653. msgbox = QtWidgets.QMessageBox()
  2654. msgbox.setText("<B>Change project units ...</B>")
  2655. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2656. "properties of all objects to be scaled accordingly. Continue?")
  2657. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2658. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2659. response = msgbox.exec_()
  2660. if response == QtWidgets.QMessageBox.Ok:
  2661. self.options_read_form()
  2662. scale_options(factor)
  2663. self.options_write_form()
  2664. self.defaults_read_form()
  2665. scale_defaults(factor)
  2666. self.defaults_write_form()
  2667. self.should_we_save = True
  2668. # change this only if the workspace is active
  2669. if self.defaults['global_workspace'] is True:
  2670. self.plotcanvas.draw_workspace()
  2671. # adjust the grid values on the main toolbar
  2672. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2673. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2674. for obj in self.collection.get_list():
  2675. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  2676. obj.convert_units(units)
  2677. # make that the properties stored in the object are also updated
  2678. self.object_changed.emit(obj)
  2679. obj.build_ui()
  2680. current = self.collection.get_active()
  2681. if current is not None:
  2682. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2683. if not isinstance(current, FlatCAMGeometry):
  2684. current.to_form()
  2685. self.plot_all()
  2686. self.inform.emit(_("[success]Converted units to %s") % self.defaults["units"])
  2687. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2688. self.set_screen_units(self.defaults["units"])
  2689. else:
  2690. # Undo toggling
  2691. self.toggle_units_ignore = True
  2692. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2693. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  2694. else:
  2695. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  2696. self.toggle_units_ignore = False
  2697. self.inform.emit(_("[WARNING_NOTCL]Units conversion cancelled."))
  2698. self.options_read_form()
  2699. self.defaults_read_form()
  2700. def on_toggle_units_click(self):
  2701. if self.options["units"] == 'MM':
  2702. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  2703. else:
  2704. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  2705. self.on_toggle_units()
  2706. def on_fullscreen(self):
  2707. self.report_usage("on_fullscreen()")
  2708. if self.toggle_fscreen is False:
  2709. if sys.platform == 'win32':
  2710. self.ui.showFullScreen()
  2711. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2712. tb.setVisible(False)
  2713. self.ui.splitter_left.setVisible(False)
  2714. self.toggle_fscreen = True
  2715. else:
  2716. if sys.platform == 'win32':
  2717. self.ui.showNormal()
  2718. self.restore_toolbar_view()
  2719. self.ui.splitter_left.setVisible(True)
  2720. self.toggle_fscreen = False
  2721. def on_toggle_plotarea(self):
  2722. self.report_usage("on_toggle_plotarea()")
  2723. try:
  2724. name = self.ui.plot_tab_area.widget(0).objectName()
  2725. except AttributeError:
  2726. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2727. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2728. self.ui.plot_tab_area.protectTab(0)
  2729. return
  2730. if name != 'plotarea':
  2731. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2732. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2733. self.ui.plot_tab_area.protectTab(0)
  2734. else:
  2735. self.ui.plot_tab_area.closeTab(0)
  2736. def on_toggle_notebook(self):
  2737. if self.ui.splitter.sizes()[0] == 0:
  2738. self.ui.splitter.setSizes([1, 1])
  2739. else:
  2740. self.ui.splitter.setSizes([0, 1])
  2741. def on_toggle_axis(self):
  2742. self.report_usage("on_toggle_axis()")
  2743. if self.toggle_axis is False:
  2744. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2745. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2746. self.plotcanvas.redraw()
  2747. self.toggle_axis = True
  2748. else:
  2749. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2750. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2751. self.plotcanvas.redraw()
  2752. self.toggle_axis = False
  2753. def on_toggle_grid(self):
  2754. self.report_usage("on_toggle_grid()")
  2755. self.ui.grid_snap_btn.trigger()
  2756. def on_toggle_code_editor(self):
  2757. self.report_usage("on_toggle_code_editor()")
  2758. if self.toggle_codeeditor is False:
  2759. # add the tab if it was closed
  2760. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, "Code Editor")
  2761. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  2762. # first clear previous text in text editor (if any)
  2763. self.ui.code_editor.clear()
  2764. # Switch plot_area to CNCJob tab
  2765. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  2766. self.toggle_codeeditor = True
  2767. else:
  2768. for idx in range(self.ui.plot_tab_area.count()):
  2769. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  2770. self.ui.plot_tab_area.closeTab(idx)
  2771. break
  2772. self.toggle_codeeditor = False
  2773. def on_options_combo_change(self, sel):
  2774. """
  2775. Called when the combo box to choose between application defaults and
  2776. project option changes value. The corresponding variables are
  2777. copied to the UI.
  2778. :param sel: The option index that was chosen.
  2779. :return: None
  2780. """
  2781. # combo_sel = self.ui.notebook.combo_options.get_active()
  2782. App.log.debug("Options --> %s" % sel)
  2783. # form = [self.defaults_form, self.options_form][sel]
  2784. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2785. if sel == 0:
  2786. self.gen_form = self.ui.general_defaults_form
  2787. self.ger_form = self.ui.gerber_defaults_form
  2788. self.exc_form = self.ui.excellon_defaults_form
  2789. self.geo_form = self.ui.geometry_defaults_form
  2790. self.cnc_form = self.ui.cncjob_defaults_form
  2791. self.tools_form = self.ui.tools_defaults_form
  2792. elif sel == 1:
  2793. self.gen_form = self.ui.general_options_form
  2794. self.ger_form = self.ui.gerber_options_form
  2795. self.exc_form = self.ui.excellon_options_form
  2796. self.geo_form = self.ui.geometry_options_form
  2797. self.cnc_form = self.ui.cncjob_options_form
  2798. self.tools_form = self.ui.tools_options_form
  2799. else:
  2800. return
  2801. try:
  2802. self.ui.general_scroll_area.takeWidget()
  2803. except:
  2804. self.log.debug("Nothing to remove")
  2805. self.ui.general_scroll_area.setWidget(self.gen_form)
  2806. self.gen_form.show()
  2807. try:
  2808. self.ui.gerber_scroll_area.takeWidget()
  2809. except:
  2810. self.log.debug("Nothing to remove")
  2811. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2812. self.ger_form.show()
  2813. try:
  2814. self.ui.excellon_scroll_area.takeWidget()
  2815. except:
  2816. self.log.debug("Nothing to remove")
  2817. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2818. self.exc_form.show()
  2819. try:
  2820. self.ui.geometry_scroll_area.takeWidget()
  2821. except:
  2822. self.log.debug("Nothing to remove")
  2823. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2824. self.geo_form.show()
  2825. try:
  2826. self.ui.cncjob_scroll_area.takeWidget()
  2827. except:
  2828. self.log.debug("Nothing to remove")
  2829. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2830. self.cnc_form.show()
  2831. try:
  2832. self.ui.tools_scroll_area.takeWidget()
  2833. except:
  2834. self.log.debug("Nothing to remove")
  2835. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2836. self.tools_form.show()
  2837. self.log.debug("Finished GUI form initialization.")
  2838. # self.options2form()
  2839. def on_excellon_defaults_button(self):
  2840. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2841. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2842. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2843. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2844. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2845. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2846. log.debug("Excellon app defaults loaded ...")
  2847. def on_excellon_options_button(self):
  2848. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2849. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2850. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2851. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2852. self.options_form_fields["excellon_zeros"].set_value('L')
  2853. self.options_form_fields["excellon_units"].set_value('INCH')
  2854. log.debug("Excellon options defaults loaded ...")
  2855. # Setting plot colors handlers
  2856. def on_pf_color_entry(self):
  2857. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2858. self.defaults['global_plot_fill'][7:9]
  2859. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2860. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2861. def on_pf_color_button(self):
  2862. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2863. c_dialog = QtWidgets.QColorDialog()
  2864. plot_fill_color = c_dialog.getColor(initial=current_color)
  2865. if plot_fill_color.isValid() is False:
  2866. return
  2867. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2868. "background-color:%s" % str(plot_fill_color.name()))
  2869. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2870. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2871. self.defaults['global_plot_fill'] = new_val
  2872. def on_pf_color_spinner(self):
  2873. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2874. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2875. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2876. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2877. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2878. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2879. def on_pf_color_slider(self):
  2880. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2881. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2882. def on_pl_color_entry(self):
  2883. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2884. self.defaults['global_plot_line'][7:9]
  2885. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2886. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2887. def on_pl_color_button(self):
  2888. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2889. # print(current_color)
  2890. c_dialog = QtWidgets.QColorDialog()
  2891. plot_line_color = c_dialog.getColor(initial=current_color)
  2892. if plot_line_color.isValid() is False:
  2893. return
  2894. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2895. "background-color:%s" % str(plot_line_color.name()))
  2896. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2897. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2898. self.defaults['global_plot_line'] = new_val_line
  2899. # Setting selection colors (left - right) handlers
  2900. def on_sf_color_entry(self):
  2901. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2902. self.defaults['global_sel_fill'][7:9]
  2903. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2904. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2905. def on_sf_color_button(self):
  2906. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2907. c_dialog = QtWidgets.QColorDialog()
  2908. plot_fill_color = c_dialog.getColor(initial=current_color)
  2909. if plot_fill_color.isValid() is False:
  2910. return
  2911. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2912. "background-color:%s" % str(plot_fill_color.name()))
  2913. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2914. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2915. self.defaults['global_sel_fill'] = new_val
  2916. def on_sf_color_spinner(self):
  2917. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2918. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2919. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2920. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2921. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2922. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2923. def on_sf_color_slider(self):
  2924. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2925. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2926. def on_sl_color_entry(self):
  2927. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2928. self.defaults['global_sel_line'][7:9]
  2929. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2930. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2931. def on_sl_color_button(self):
  2932. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2933. c_dialog = QtWidgets.QColorDialog()
  2934. plot_line_color = c_dialog.getColor(initial=current_color)
  2935. if plot_line_color.isValid() is False:
  2936. return
  2937. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2938. "background-color:%s" % str(plot_line_color.name()))
  2939. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2940. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2941. self.defaults['global_sel_line'] = new_val_line
  2942. # Setting selection colors (right - left) handlers
  2943. def on_alt_sf_color_entry(self):
  2944. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  2945. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2946. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2947. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2948. def on_alt_sf_color_button(self):
  2949. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2950. c_dialog = QtWidgets.QColorDialog()
  2951. plot_fill_color = c_dialog.getColor(initial=current_color)
  2952. if plot_fill_color.isValid() is False:
  2953. return
  2954. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2955. "background-color:%s" % str(plot_fill_color.name()))
  2956. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2957. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2958. self.defaults['global_alt_sel_fill'] = new_val
  2959. def on_alt_sf_color_spinner(self):
  2960. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2961. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2962. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2963. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2964. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2965. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2966. def on_alt_sf_color_slider(self):
  2967. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2968. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2969. def on_alt_sl_color_entry(self):
  2970. self.defaults['global_alt_sel_line'] = self.ui.general_defaults_form.general_gui_group \
  2971. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2972. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2973. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2974. def on_alt_sl_color_button(self):
  2975. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2976. c_dialog = QtWidgets.QColorDialog()
  2977. plot_line_color = c_dialog.getColor(initial=current_color)
  2978. if plot_line_color.isValid() is False:
  2979. return
  2980. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2981. "background-color:%s" % str(plot_line_color.name()))
  2982. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2983. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2984. self.defaults['global_alt_sel_line'] = new_val_line
  2985. # Setting Editor colors
  2986. def on_draw_color_entry(self):
  2987. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  2988. .draw_color_entry.get_value()
  2989. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2990. "background-color:%s" % str(self.defaults['global_draw_color']))
  2991. def on_draw_color_button(self):
  2992. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2993. c_dialog = QtWidgets.QColorDialog()
  2994. draw_color = c_dialog.getColor(initial=current_color)
  2995. if draw_color.isValid() is False:
  2996. return
  2997. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2998. "background-color:%s" % str(draw_color.name()))
  2999. new_val = str(draw_color.name())
  3000. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3001. self.defaults['global_draw_color'] = new_val
  3002. def on_sel_draw_color_entry(self):
  3003. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3004. .sel_draw_color_entry.get_value()
  3005. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3006. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3007. def on_sel_draw_color_button(self):
  3008. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3009. c_dialog = QtWidgets.QColorDialog()
  3010. sel_draw_color = c_dialog.getColor(initial=current_color)
  3011. if sel_draw_color.isValid() is False:
  3012. return
  3013. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3014. "background-color:%s" % str(sel_draw_color.name()))
  3015. new_val_sel = str(sel_draw_color.name())
  3016. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3017. self.defaults['global_sel_draw_color'] = new_val_sel
  3018. def on_deselect_all(self):
  3019. self.collection.set_all_inactive()
  3020. self.delete_selection_shape()
  3021. def on_workspace_modified(self):
  3022. self.save_defaults(silent=True)
  3023. self.plotcanvas.draw_workspace()
  3024. def on_workspace(self):
  3025. self.report_usage("on_workspace()")
  3026. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3027. self.plotcanvas.restore_workspace()
  3028. else:
  3029. self.plotcanvas.delete_workspace()
  3030. self.save_defaults(silent=True)
  3031. def on_workspace_menu(self):
  3032. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3033. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3034. else:
  3035. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3036. self.on_workspace()
  3037. def on_layout(self, index, lay=None):
  3038. self.report_usage("on_layout()")
  3039. if lay:
  3040. current_layout = lay
  3041. else:
  3042. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value().lower()
  3043. settings = QSettings("Open Source", "FlatCAM")
  3044. settings.setValue('layout', current_layout)
  3045. # This will write the setting to the platform specific storage.
  3046. del settings
  3047. # first remove the toolbars:
  3048. self.ui.removeToolBar(self.ui.toolbarfile)
  3049. self.ui.removeToolBar(self.ui.toolbargeo)
  3050. self.ui.removeToolBar(self.ui.toolbarview)
  3051. self.ui.removeToolBar(self.ui.toolbarshell)
  3052. self.ui.removeToolBar(self.ui.toolbartools)
  3053. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3054. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3055. self.ui.removeToolBar(self.ui.snap_toolbar)
  3056. self.ui.removeToolBar(self.ui.toolbarshell)
  3057. if current_layout == 'standard':
  3058. ### TOOLBAR INSTALLATION ###
  3059. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3060. self.ui.toolbarfile.setObjectName('File_TB')
  3061. self.ui.addToolBar(self.ui.toolbarfile)
  3062. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3063. self.ui.toolbargeo.setObjectName('Edit_TB')
  3064. self.ui.addToolBar(self.ui.toolbargeo)
  3065. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3066. self.ui.toolbarview.setObjectName('View_TB')
  3067. self.ui.addToolBar(self.ui.toolbarview)
  3068. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3069. self.ui.toolbarshell.setObjectName('Shell_TB')
  3070. self.ui.addToolBar(self.ui.toolbarshell)
  3071. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3072. self.ui.toolbartools.setObjectName('Tools_TB')
  3073. self.ui.addToolBar(self.ui.toolbartools)
  3074. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3075. self.ui.exc_edit_toolbar.setVisible(False)
  3076. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3077. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3078. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3079. self.ui.geo_edit_toolbar.setVisible(False)
  3080. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3081. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3082. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3083. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3084. # self.ui.snap_toolbar.setMaximumHeight(30)
  3085. self.ui.addToolBar(self.ui.snap_toolbar)
  3086. self.ui.corner_snap_btn.setVisible(False)
  3087. self.ui.snap_magnet.setVisible(False)
  3088. elif current_layout == 'compact':
  3089. ### TOOLBAR INSTALLATION ###
  3090. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3091. self.ui.toolbarfile.setObjectName('File_TB')
  3092. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3093. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3094. self.ui.toolbargeo.setObjectName('Edit_TB')
  3095. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3096. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3097. self.ui.toolbarview.setObjectName('View_TB')
  3098. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3099. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3100. self.ui.toolbarshell.setObjectName('Shell_TB')
  3101. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3102. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3103. self.ui.toolbartools.setObjectName('Tools_TB')
  3104. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3105. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3106. # self.ui.geo_edit_toolbar.setVisible(False)
  3107. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3108. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3109. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3110. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3111. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3112. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3113. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3114. self.ui.snap_toolbar.setMaximumHeight(30)
  3115. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3116. self.ui.corner_snap_btn.setVisible(True)
  3117. self.ui.snap_magnet.setVisible(True)
  3118. # add all the actions to the toolbars
  3119. self.ui.populate_toolbars()
  3120. # reconnect all the signals to the toolbar actions
  3121. self.connect_toolbar_signals()
  3122. self.ui.grid_snap_btn.setChecked(True)
  3123. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3124. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3125. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3126. self.ui.grid_gap_link_cb.setChecked(True)
  3127. def on_cnc_custom_parameters(self, signal_text):
  3128. if signal_text == 'Parameters':
  3129. return
  3130. else:
  3131. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3132. def on_save_button(self):
  3133. self.save_defaults(silent=False)
  3134. # load the defaults so they are updated into the app
  3135. self.load_defaults(filename='current_defaults')
  3136. # Re-fresh project options
  3137. self.on_options_app2project()
  3138. def handleOpen(self):
  3139. self.report_usage("handleOpen()")
  3140. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3141. "All Files (*.*)"
  3142. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  3143. caption=_('Open file'), directory=self.get_last_folder(), filter=filter_group)
  3144. if path:
  3145. file = QtCore.QFile(path)
  3146. if file.open(QtCore.QIODevice.ReadOnly):
  3147. stream = QtCore.QTextStream(file)
  3148. self.gcode_edited = stream.readAll()
  3149. self.ui.code_editor.setPlainText(self.gcode_edited)
  3150. file.close()
  3151. def handlePrint(self):
  3152. self.report_usage("handlePrint()")
  3153. dialog = QtPrintSupport.QPrintDialog()
  3154. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3155. self.ui.code_editor.document().print_(dialog.printer())
  3156. def handlePreview(self):
  3157. self.report_usage("handlePreview()")
  3158. dialog = QtPrintSupport.QPrintPreviewDialog()
  3159. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3160. dialog.exec_()
  3161. def handleTextChanged(self):
  3162. self.report_usage("handleTextChanged()")
  3163. # enable = not self.ui.code_editor.document().isEmpty()
  3164. # self.ui.buttonPrint.setEnabled(enable)
  3165. # self.ui.buttonPreview.setEnabled(enable)
  3166. pass
  3167. def handleSaveGCode(self, signal, name=None, filt=None):
  3168. self.report_usage("handleSaveGCode()")
  3169. if filt:
  3170. _filter_ = filt
  3171. else:
  3172. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3173. "All Files (*.*)"
  3174. if name:
  3175. obj_name = name
  3176. else:
  3177. try:
  3178. obj_name = self.collection.get_active().options['name']
  3179. except AttributeError:
  3180. obj_name = 'file'
  3181. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3182. try:
  3183. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3184. caption=_("Export G-Code ..."),
  3185. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3186. filter=_filter_
  3187. )[0])
  3188. except TypeError:
  3189. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3190. if filename == "":
  3191. self.inform.emit(_("[WARNING_NOTCL]Export Code cancelled."))
  3192. return
  3193. else:
  3194. try:
  3195. my_gcode = self.ui.code_editor.toPlainText()
  3196. with open(filename, 'w') as f:
  3197. for line in my_gcode:
  3198. f.write(line)
  3199. except FileNotFoundError:
  3200. self.inform.emit(_("[WARNING] No such file or directory"))
  3201. return
  3202. # Just for adding it to the recent files list.
  3203. self.file_opened.emit("cncjob", filename)
  3204. self.file_saved.emit("cncjob", filename)
  3205. self.inform.emit(_("Saved to: %s") % filename)
  3206. def handleFindGCode(self):
  3207. self.report_usage("handleFindGCode()")
  3208. flags = QtGui.QTextDocument.FindCaseSensitively
  3209. text_to_be_found = self.ui.entryFind.get_value()
  3210. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3211. if r is False:
  3212. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3213. def handleReplaceGCode(self):
  3214. self.report_usage("handleReplaceGCode()")
  3215. old = self.ui.entryFind.get_value()
  3216. new = self.ui.entryReplace.get_value()
  3217. if self.ui.sel_all_cb.isChecked():
  3218. while True:
  3219. cursor = self.ui.code_editor.textCursor()
  3220. cursor.beginEditBlock()
  3221. flags = QtGui.QTextDocument.FindCaseSensitively
  3222. # self.ui.editor is the QPlainTextEdit
  3223. r = self.ui.code_editor.find(str(old), flags)
  3224. if r:
  3225. qc = self.ui.code_editor.textCursor()
  3226. if qc.hasSelection():
  3227. qc.insertText(new)
  3228. else:
  3229. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3230. break
  3231. # Mark end of undo block
  3232. cursor.endEditBlock()
  3233. else:
  3234. cursor = self.ui.code_editor.textCursor()
  3235. cursor.beginEditBlock()
  3236. qc = self.ui.code_editor.textCursor()
  3237. if qc.hasSelection():
  3238. qc.insertText(new)
  3239. # Mark end of undo block
  3240. cursor.endEditBlock()
  3241. def on_tool_add_keypress(self):
  3242. ## Current application units in Upper Case
  3243. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3244. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3245. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3246. if notebook_widget_name == 'selected_tab':
  3247. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3248. # Tool add works for Geometry only if Advanced is True in Preferences
  3249. if self.defaults["global_app_level"] == 'a':
  3250. tool_add_popup = FCInputDialog(title="New Tool ...",
  3251. text='Enter a Tool Diameter:',
  3252. min=0.0000, max=99.9999, decimals=4)
  3253. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3254. val, ok = tool_add_popup.get_value()
  3255. if ok:
  3256. if float(val) == 0:
  3257. self.inform.emit(
  3258. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3259. return
  3260. self.collection.get_active().on_tool_add(dia=float(val))
  3261. else:
  3262. self.inform.emit(
  3263. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3264. else:
  3265. msgbox = QtWidgets.QMessageBox()
  3266. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3267. "Go to Preferences -> General - Show Advanced Options."))
  3268. msgbox.setWindowTitle("Tool adding ...")
  3269. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3270. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3271. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3272. msgbox.exec_()
  3273. # work only if the notebook tab on focus is the Tools_Tab
  3274. if notebook_widget_name == 'tool_tab':
  3275. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3276. tool_add_popup = FCInputDialog(title="New Tool ...",
  3277. text='Enter a Tool Diameter:',
  3278. min=0.0000, max=99.9999, decimals=4)
  3279. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3280. val, ok = tool_add_popup.get_value()
  3281. # and only if the tool is NCC Tool
  3282. if tool_widget == self.ncclear_tool.toolName:
  3283. if ok:
  3284. if float(val) == 0:
  3285. self.inform.emit(
  3286. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3287. return
  3288. self.ncclear_tool.on_tool_add(dia=float(val))
  3289. else:
  3290. self.inform.emit(
  3291. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3292. # and only if the tool is Paint Area Tool
  3293. elif tool_widget == self.paint_tool.toolName:
  3294. if ok:
  3295. if float(val) == 0:
  3296. self.inform.emit(
  3297. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3298. return
  3299. self.paint_tool.on_tool_add(dia=float(val))
  3300. else:
  3301. self.inform.emit(
  3302. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3303. # and only if the tool is Solder Paste Dispensing Tool
  3304. elif tool_widget == self.paste_tool.toolName:
  3305. if ok:
  3306. if float(val) == 0:
  3307. self.inform.emit(
  3308. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3309. return
  3310. self.paste_tool.on_tool_add(dia=float(val))
  3311. else:
  3312. self.inform.emit(
  3313. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3314. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3315. # See description bellow.
  3316. def on_delete_keypress(self):
  3317. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3318. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3319. if notebook_widget_name == 'selected_tab':
  3320. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3321. self.collection.get_active().on_tool_delete()
  3322. # work only if the notebook tab on focus is the Tools_Tab
  3323. elif notebook_widget_name == 'tool_tab':
  3324. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3325. # and only if the tool is NCC Tool
  3326. if tool_widget == self.ncclear_tool.toolName:
  3327. self.ncclear_tool.on_tool_delete()
  3328. # and only if the tool is Paint Tool
  3329. elif tool_widget == self.paint_tool.toolName:
  3330. self.paint_tool.on_tool_delete()
  3331. # and only if the tool is Solder Paste Dispensing Tool
  3332. elif tool_widget == self.paste_tool.toolName:
  3333. self.paste_tool.on_tool_delete()
  3334. else:
  3335. self.on_delete()
  3336. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3337. # some screens you have to be careful where you hover with your mouse.
  3338. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3339. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3340. # Complicated, I know :)
  3341. def on_delete(self):
  3342. """
  3343. Delete the currently selected FlatCAMObjs.
  3344. :return: None
  3345. """
  3346. self.report_usage("on_delete()")
  3347. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3348. # a geometry object before we update it.
  3349. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3350. if self.collection.get_active():
  3351. self.log.debug("on_delete()")
  3352. self.report_usage("on_delete")
  3353. while (self.collection.get_active()):
  3354. self.delete_first_selected()
  3355. self.inform.emit(_("Object(s) deleted ..."))
  3356. # make sure that the selection shape is deleted, too
  3357. self.delete_selection_shape()
  3358. else:
  3359. self.inform.emit(_("Failed. No object(s) selected..."))
  3360. else:
  3361. self.inform.emit(_("Save the work in Editor and try again ..."))
  3362. def on_set_origin(self):
  3363. """
  3364. Set the origin to the left mouse click position
  3365. :return: None
  3366. """
  3367. #display the message for the user
  3368. #and ask him to click on the desired position
  3369. self.report_usage("on_set_origin()")
  3370. self.inform.emit(_('Click to set the origin ...'))
  3371. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3372. def on_jump_to(self):
  3373. """
  3374. Jump to a location by setting the mouse cursor location
  3375. :return:
  3376. """
  3377. self.report_usage("on_jump_to()")
  3378. dia_box = Dialog_box(title=_("Jump to ..."),
  3379. label=_("Enter the coordinates in format X,Y:"),
  3380. icon=QtGui.QIcon('share/jump_to16.png'))
  3381. if dia_box.ok is True:
  3382. try:
  3383. location = eval(dia_box.location)
  3384. if not isinstance(location, tuple):
  3385. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3386. return
  3387. except:
  3388. return
  3389. else:
  3390. return
  3391. self.plotcanvas.fit_center(loc=location)
  3392. cursor = QtGui.QCursor()
  3393. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3394. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3395. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3396. self.inform.emit(_("Done."))
  3397. def on_copy_object(self):
  3398. self.report_usage("on_copy_object()")
  3399. def initialize(obj_init, app):
  3400. obj_init.solid_geometry = obj.solid_geometry
  3401. try:
  3402. if obj.tools:
  3403. obj_init.tools = obj.tools
  3404. except Exception as e:
  3405. log.debug("on_copy_object() --> %s" % str(e))
  3406. def initialize_excellon(obj_init, app):
  3407. obj_init.tools = obj.tools
  3408. # drills are offset, so they need to be deep copied
  3409. obj_init.drills = deepcopy(obj.drills)
  3410. # slots are offset, so they need to be deep copied
  3411. obj_init.slots = deepcopy(obj.slots)
  3412. obj_init.create_geometry()
  3413. for obj in self.collection.get_selected():
  3414. obj_name = obj.options["name"]
  3415. try:
  3416. if isinstance(obj, FlatCAMExcellon):
  3417. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3418. elif isinstance(obj,FlatCAMGerber):
  3419. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3420. elif isinstance(obj,FlatCAMGeometry):
  3421. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3422. except Exception as e:
  3423. return "Operation failed: %s" % str(e)
  3424. def on_copy_object2(self, custom_name):
  3425. def initialize_geometry(obj_init, app):
  3426. obj_init.solid_geometry = obj.solid_geometry
  3427. try:
  3428. if obj.tools:
  3429. obj_init.tools = obj.tools
  3430. except Exception as e:
  3431. log.debug("on_copy_object2() --> %s" % str(e))
  3432. def initialize_gerber(obj_init, app):
  3433. obj_init.solid_geometry = obj.solid_geometry
  3434. obj_init.apertures = deepcopy(obj.apertures)
  3435. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3436. def initialize_excellon(obj_init, app):
  3437. obj_init.tools = obj.tools
  3438. # drills are offset, so they need to be deep copied
  3439. obj_init.drills = deepcopy(obj.drills)
  3440. # slots are offset, so they need to be deep copied
  3441. obj_init.slots = deepcopy(obj.slots)
  3442. obj_init.create_geometry()
  3443. for obj in self.collection.get_selected():
  3444. obj_name = obj.options["name"]
  3445. try:
  3446. if isinstance(obj, FlatCAMExcellon):
  3447. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3448. elif isinstance(obj,FlatCAMGerber):
  3449. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3450. elif isinstance(obj,FlatCAMGeometry):
  3451. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3452. except Exception as e:
  3453. return "Operation failed: %s" % str(e)
  3454. def on_rename_object(self, text):
  3455. self.report_usage("on_rename_object()")
  3456. named_obj = self.collection.get_active()
  3457. for obj in named_obj:
  3458. if obj is list:
  3459. self.on_rename_object(text)
  3460. else:
  3461. try:
  3462. obj.options['name'] = text
  3463. except:
  3464. log.warning("Could not rename the object in the list")
  3465. def on_copy_object_as_geometry(self):
  3466. self.report_usage("on_copy_object_as_geometry()")
  3467. def initialize(obj_init, app):
  3468. obj_init.solid_geometry = obj.solid_geometry
  3469. if obj.tools:
  3470. obj_init.tools = obj.tools
  3471. def initialize_excellon(obj, app):
  3472. objs = self.collection.get_selected()
  3473. FlatCAMGeometry.merge(objs, obj)
  3474. for obj in self.collection.get_selected():
  3475. obj_name = obj.options["name"]
  3476. try:
  3477. if isinstance(obj, FlatCAMExcellon):
  3478. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3479. else:
  3480. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3481. except Exception as e:
  3482. return "Operation failed: %s" % str(e)
  3483. def on_set_zero_click(self, event):
  3484. #this function will be available only for mouse left click
  3485. pos =[]
  3486. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3487. if event.button == 1:
  3488. if self.grid_status() == True:
  3489. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3490. else:
  3491. pos = pos_canvas
  3492. x = 0 - pos[0]
  3493. y = 0 - pos[1]
  3494. for obj in self.collection.get_list():
  3495. obj.offset((x,y))
  3496. self.object_changed.emit(obj)
  3497. obj.plot()
  3498. # Update the object bounding box options
  3499. a, b, c, d = obj.bounds()
  3500. obj.options['xmin'] = a
  3501. obj.options['ymin'] = b
  3502. obj.options['xmax'] = c
  3503. obj.options['ymax'] = d
  3504. # self.plot_all(zoom=False)
  3505. self.inform.emit(_('[success] Origin set ...'))
  3506. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3507. self.should_we_save = True
  3508. def on_selectall(self):
  3509. self.report_usage("on_selectall()")
  3510. # delete the possible selection box around a possible selected object
  3511. self.delete_selection_shape()
  3512. for name in self.collection.get_names():
  3513. self.collection.set_active(name)
  3514. curr_sel_obj = self.collection.get_by_name(name)
  3515. # create the selection box around the selected object
  3516. self.draw_selection_shape(curr_sel_obj)
  3517. def on_preferences(self):
  3518. # add the tab if it was closed
  3519. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  3520. # delete the absolute and relative position and messages in the infobar
  3521. self.ui.position_label.setText("")
  3522. self.ui.rel_position_label.setText("")
  3523. # Switch plot_area to preferences page
  3524. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3525. self.ui.show()
  3526. def on_flipy(self):
  3527. self.report_usage("on_flipy()")
  3528. obj_list = self.collection.get_selected()
  3529. xminlist = []
  3530. yminlist = []
  3531. xmaxlist = []
  3532. ymaxlist = []
  3533. if not obj_list:
  3534. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  3535. else:
  3536. try:
  3537. # first get a bounding box to fit all
  3538. for obj in obj_list:
  3539. xmin, ymin, xmax, ymax = obj.bounds()
  3540. xminlist.append(xmin)
  3541. yminlist.append(ymin)
  3542. xmaxlist.append(xmax)
  3543. ymaxlist.append(ymax)
  3544. # get the minimum x,y and maximum x,y for all objects selected
  3545. xminimal = min(xminlist)
  3546. yminimal = min(yminlist)
  3547. xmaximal = max(xmaxlist)
  3548. ymaximal = max(ymaxlist)
  3549. px = 0.5 * (xminimal + xmaximal)
  3550. py = 0.5 * (yminimal + ymaximal)
  3551. # execute mirroring
  3552. for obj in obj_list:
  3553. obj.mirror('X', [px, py])
  3554. obj.plot()
  3555. self.object_changed.emit(obj)
  3556. self.inform.emit(_("[success] Flip on Y axis done."))
  3557. except Exception as e:
  3558. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3559. return
  3560. def on_flipx(self):
  3561. self.report_usage("on_flipx()")
  3562. obj_list = self.collection.get_selected()
  3563. xminlist = []
  3564. yminlist = []
  3565. xmaxlist = []
  3566. ymaxlist = []
  3567. if not obj_list:
  3568. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  3569. else:
  3570. try:
  3571. # first get a bounding box to fit all
  3572. for obj in obj_list:
  3573. xmin, ymin, xmax, ymax = obj.bounds()
  3574. xminlist.append(xmin)
  3575. yminlist.append(ymin)
  3576. xmaxlist.append(xmax)
  3577. ymaxlist.append(ymax)
  3578. # get the minimum x,y and maximum x,y for all objects selected
  3579. xminimal = min(xminlist)
  3580. yminimal = min(yminlist)
  3581. xmaximal = max(xmaxlist)
  3582. ymaximal = max(ymaxlist)
  3583. px = 0.5 * (xminimal + xmaximal)
  3584. py = 0.5 * (yminimal + ymaximal)
  3585. # execute mirroring
  3586. for obj in obj_list:
  3587. obj.mirror('Y', [px, py])
  3588. obj.plot()
  3589. self.object_changed.emit(obj)
  3590. self.inform.emit(_("[success] Flip on X axis done."))
  3591. except Exception as e:
  3592. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3593. return
  3594. def on_rotate(self, silent=False, preset=None):
  3595. self.report_usage("on_rotate()")
  3596. obj_list = self.collection.get_selected()
  3597. xminlist = []
  3598. yminlist = []
  3599. xmaxlist = []
  3600. ymaxlist = []
  3601. if not obj_list:
  3602. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  3603. else:
  3604. if silent is False:
  3605. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3606. min=-360, max=360, decimals=4,
  3607. init_val=float(self.defaults['tools_transform_rotate']))
  3608. num, ok = rotatebox.get_value()
  3609. else:
  3610. num = preset
  3611. ok = True
  3612. if ok:
  3613. try:
  3614. # first get a bounding box to fit all
  3615. for obj in obj_list:
  3616. xmin, ymin, xmax, ymax = obj.bounds()
  3617. xminlist.append(xmin)
  3618. yminlist.append(ymin)
  3619. xmaxlist.append(xmax)
  3620. ymaxlist.append(ymax)
  3621. # get the minimum x,y and maximum x,y for all objects selected
  3622. xminimal = min(xminlist)
  3623. yminimal = min(yminlist)
  3624. xmaximal = max(xmaxlist)
  3625. ymaximal = max(ymaxlist)
  3626. px = 0.5 * (xminimal + xmaximal)
  3627. py = 0.5 * (yminimal + ymaximal)
  3628. for sel_obj in obj_list:
  3629. sel_obj.rotate(-float(num), point=(px, py))
  3630. sel_obj.plot()
  3631. self.object_changed.emit(sel_obj)
  3632. self.inform.emit(_("[success] Rotation done."))
  3633. except Exception as e:
  3634. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  3635. return
  3636. def on_skewx(self):
  3637. self.report_usage("on_skewx()")
  3638. obj_list = self.collection.get_selected()
  3639. xminlist = []
  3640. yminlist = []
  3641. if not obj_list:
  3642. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  3643. else:
  3644. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3645. min=-360, max=360, decimals=4,
  3646. init_val=float(self.defaults['tools_transform_skew_x']))
  3647. num, ok = skewxbox.get_value()
  3648. if ok:
  3649. # first get a bounding box to fit all
  3650. for obj in obj_list:
  3651. xmin, ymin, xmax, ymax = obj.bounds()
  3652. xminlist.append(xmin)
  3653. yminlist.append(ymin)
  3654. # get the minimum x,y and maximum x,y for all objects selected
  3655. xminimal = min(xminlist)
  3656. yminimal = min(yminlist)
  3657. for obj in obj_list:
  3658. obj.skew(num, 0, point=(xminimal, yminimal))
  3659. obj.plot()
  3660. self.object_changed.emit(obj)
  3661. self.inform.emit(_("[success] Skew on X axis done."))
  3662. def on_skewy(self):
  3663. self.report_usage("on_skewy()")
  3664. obj_list = self.collection.get_selected()
  3665. xminlist = []
  3666. yminlist = []
  3667. if not obj_list:
  3668. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  3669. else:
  3670. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3671. min=-360, max=360, decimals=4,
  3672. init_val=float(self.defaults['tools_transform_skew_y']))
  3673. num, ok = skewybox.get_value()
  3674. if ok:
  3675. # first get a bounding box to fit all
  3676. for obj in obj_list:
  3677. xmin, ymin, xmax, ymax = obj.bounds()
  3678. xminlist.append(xmin)
  3679. yminlist.append(ymin)
  3680. # get the minimum x,y and maximum x,y for all objects selected
  3681. xminimal = min(xminlist)
  3682. yminimal = min(yminlist)
  3683. for obj in obj_list:
  3684. obj.skew(0, num, point=(xminimal, yminimal))
  3685. obj.plot()
  3686. self.object_changed.emit(obj)
  3687. self.inform.emit(_("[success] Skew on Y axis done."))
  3688. def delete_first_selected(self):
  3689. # Keep this for later
  3690. try:
  3691. name = self.collection.get_active().options["name"]
  3692. except AttributeError:
  3693. self.log.debug("Nothing selected for deletion")
  3694. return
  3695. # Remove plot
  3696. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3697. # self.plotcanvas.auto_adjust_axes()
  3698. # Clear form
  3699. self.setup_component_editor()
  3700. # Remove from dictionary
  3701. self.collection.delete_active()
  3702. self.inform.emit("Object deleted: %s" % name)
  3703. def on_plots_updated(self):
  3704. """
  3705. Callback used to report when the plots have changed.
  3706. Adjust axes and zooms to fit.
  3707. :return: None
  3708. """
  3709. # self.plotcanvas.auto_adjust_axes()
  3710. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3711. self.on_zoom_fit(None)
  3712. # TODO: Rework toolbar 'clear', 'replot' functions
  3713. def on_toolbar_replot(self):
  3714. """
  3715. Callback for toolbar button. Re-plots all objects.
  3716. :return: None
  3717. """
  3718. self.report_usage("on_toolbar_replot")
  3719. self.log.debug("on_toolbar_replot()")
  3720. try:
  3721. self.collection.get_active().read_form()
  3722. except AttributeError:
  3723. self.log.debug("on_toolbar_replot(): AttributeError")
  3724. pass
  3725. self.plot_all()
  3726. def on_row_activated(self, index):
  3727. if index.isValid():
  3728. if index.internalPointer().parent_item != self.collection.root_item:
  3729. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3730. def grid_status(self):
  3731. if self.ui.grid_snap_btn.isChecked():
  3732. return 1
  3733. else:
  3734. return 0
  3735. def populate_cmenu_grids(self):
  3736. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3737. self.ui.cmenu_gridmenu.clear()
  3738. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  3739. for grid in sorted_list:
  3740. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  3741. action.triggered.connect(self.set_grid)
  3742. self.ui.cmenu_gridmenu.addSeparator()
  3743. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  3744. grid_add.triggered.connect(self.on_grid_add)
  3745. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  3746. grid_delete.triggered.connect(self.on_grid_delete)
  3747. def set_grid(self):
  3748. self.ui.grid_gap_x_entry.setText(self.sender().text())
  3749. self.ui.grid_gap_y_entry.setText(self.sender().text())
  3750. def on_grid_add(self):
  3751. ## Current application units in lower Case
  3752. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3753. grid_add_popup = FCInputDialog(title="New Grid ...",
  3754. text='Enter a Grid VAlue:',
  3755. min=0.0000, max=99.9999, decimals=4)
  3756. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  3757. val, ok = grid_add_popup.get_value()
  3758. if ok:
  3759. if float(val) == 0:
  3760. self.inform.emit(
  3761. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  3762. return
  3763. else:
  3764. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  3765. self.defaults["global_grid_context_menu"][str(units)].append(val)
  3766. self.inform.emit(
  3767. _("[success] New Grid added ..."))
  3768. else:
  3769. self.inform.emit(
  3770. _("[WARNING_NOTCL] Grid already exists ..."))
  3771. else:
  3772. self.inform.emit(
  3773. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  3774. def on_grid_delete(self):
  3775. ## Current application units in lower Case
  3776. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  3777. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  3778. text='Enter a Grid Value:',
  3779. min=0.0000, max=99.9999, decimals=4)
  3780. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  3781. val, ok = grid_del_popup.get_value()
  3782. if ok:
  3783. if float(val) == 0:
  3784. self.inform.emit(
  3785. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  3786. return
  3787. else:
  3788. try:
  3789. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  3790. except ValueError:
  3791. self.inform.emit(
  3792. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  3793. return
  3794. self.inform.emit(
  3795. _("[success] Grid Value deleted ..."))
  3796. else:
  3797. self.inform.emit(
  3798. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  3799. def on_shortcut_list(self):
  3800. self.report_usage("on_shortcut_list()")
  3801. # add the tab if it was closed
  3802. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3803. # delete the absolute and relative position and messages in the infobar
  3804. self.ui.position_label.setText("")
  3805. self.ui.rel_position_label.setText("")
  3806. # Switch plot_area to preferences page
  3807. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3808. self.ui.show()
  3809. def on_select_tab(self, name):
  3810. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  3811. if self.ui.splitter.sizes()[0] == 0:
  3812. self.ui.splitter.setSizes([1, 1])
  3813. else:
  3814. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  3815. self.ui.splitter.setSizes([0, 1])
  3816. if name == 'project':
  3817. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3818. elif name == 'selected':
  3819. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3820. elif name == 'tool':
  3821. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  3822. def on_copy_name(self):
  3823. self.report_usage("on_copy_name()")
  3824. obj = self.collection.get_active()
  3825. try:
  3826. name = obj.options["name"]
  3827. except AttributeError:
  3828. log.debug("on_copy_name() --> No object selected to copy it's name")
  3829. self.inform.emit(_("[WARNING_NOTCL]No object selected to copy it's name"))
  3830. return
  3831. self.clipboard.setText(name)
  3832. self.inform.emit(_("Name copied on clipboard ..."))
  3833. def on_mouse_click_over_plot(self, event):
  3834. """
  3835. Default actions are:
  3836. :param event: Contains information about the event, like which button
  3837. was clicked, the pixel coordinates and the axes coordinates.
  3838. :return: None
  3839. """
  3840. self.pos = []
  3841. # So it can receive key presses
  3842. self.plotcanvas.vispy_canvas.native.setFocus()
  3843. # Set the mouse button for panning
  3844. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3845. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3846. if self.grid_status() == True:
  3847. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3848. self.app_cursor.enabled = True
  3849. else:
  3850. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3851. self.app_cursor.enabled = False
  3852. try:
  3853. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3854. if event.button == 1:
  3855. # Reset here the relative coordinates so there is a new reference on the click position
  3856. if self.rel_point1 is None:
  3857. self.rel_point1 = self.pos
  3858. else:
  3859. self.rel_point2 = copy(self.rel_point1)
  3860. self.rel_point1 = self.pos
  3861. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3862. if modifiers == QtCore.Qt.ShiftModifier:
  3863. # do not auto open the Project Tab
  3864. self.click_noproject = True
  3865. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3866. return
  3867. self.on_mouse_move_over_plot(event, origin_click=True)
  3868. except Exception as e:
  3869. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3870. def on_double_click_over_plot(self, event):
  3871. self.doubleclick = True
  3872. def on_mouse_move_over_plot(self, event, origin_click=None):
  3873. """
  3874. Callback for the mouse motion event over the plot. This event is generated
  3875. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3876. For details, see: http://matplotlib.org/users/event_handling.html
  3877. :param event: Contains information about the event.
  3878. :param origin_click
  3879. :return: None
  3880. """
  3881. # So it can receive key presses
  3882. self.plotcanvas.vispy_canvas.native.setFocus()
  3883. self.pos_jump = event.pos
  3884. if origin_click is True:
  3885. pass
  3886. else:
  3887. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3888. if event.button == 2:
  3889. self.panning_action = True
  3890. return
  3891. else:
  3892. self.panning_action = False
  3893. if self.rel_point1 is not None:
  3894. try: # May fail in case mouse not within axes
  3895. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3896. if self.grid_status():
  3897. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3898. self.app_cursor.enabled = True
  3899. # Update cursor
  3900. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3901. else:
  3902. pos = (pos_canvas[0], pos_canvas[1])
  3903. self.app_cursor.enabled = False
  3904. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3905. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3906. dx = pos[0] - self.rel_point1[0]
  3907. dy = pos[1] - self.rel_point1[1]
  3908. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3909. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3910. self.mouse = [pos[0], pos[1]]
  3911. # if the mouse is moved and the LMB is clicked then the action is a selection
  3912. if event.is_dragging == 1 and event.button == 1:
  3913. self.delete_selection_shape()
  3914. if dx < 0:
  3915. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3916. face_color=self.defaults['global_alt_sel_fill'])
  3917. self.selection_type = False
  3918. else:
  3919. self.draw_moving_selection_shape(self.pos, pos)
  3920. self.selection_type = True
  3921. # hover effect - enabled in Preferences -> General -> GUI Settings
  3922. if self.defaults['global_hover']:
  3923. for obj in self.collection.get_list():
  3924. try:
  3925. # select the object(s) only if it is enabled (plotted)
  3926. if obj.options['plot']:
  3927. if obj not in self.collection.get_selected():
  3928. poly_obj = Polygon(
  3929. [(obj.options['xmin'], obj.options['ymin']),
  3930. (obj.options['xmax'], obj.options['ymin']),
  3931. (obj.options['xmax'], obj.options['ymax']),
  3932. (obj.options['xmin'], obj.options['ymax'])]
  3933. )
  3934. if Point(pos).within(poly_obj):
  3935. if obj.isHovering is False:
  3936. obj.isHovering = True
  3937. obj.notHovering = True
  3938. # create the selection box around the selected object
  3939. self.draw_hover_shape(obj, color='#d1e0e0')
  3940. else:
  3941. if obj.notHovering is True:
  3942. obj.notHovering = False
  3943. obj.isHovering = False
  3944. self.delete_hover_shape()
  3945. except:
  3946. # the Exception here will happen if we try to select on screen and we have an
  3947. # newly (and empty) just created Geometry or Excellon object that do not have the
  3948. # xmin, xmax, ymin, ymax options.
  3949. # In this case poly_obj creation (see above) will fail
  3950. pass
  3951. except:
  3952. self.ui.position_label.setText("")
  3953. self.ui.rel_position_label.setText("")
  3954. self.mouse = None
  3955. def on_mouse_click_release_over_plot(self, event):
  3956. """
  3957. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3958. and has been registered in ''self.__init__()''.
  3959. :param event: contains information about the event.
  3960. :return:
  3961. """
  3962. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3963. if self.grid_status():
  3964. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3965. else:
  3966. pos = (pos_canvas[0], pos_canvas[1])
  3967. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3968. # canvas menu
  3969. try:
  3970. if event.button == 2: # right click
  3971. if self.panning_action is True:
  3972. self.panning_action = False
  3973. else:
  3974. self.cursor = QtGui.QCursor()
  3975. self.populate_cmenu_grids()
  3976. self.ui.popMenu.popup(self.cursor.pos())
  3977. except Exception as e:
  3978. log.warning("Error: %s" % str(e))
  3979. return
  3980. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3981. # selection and then select a type of selection ("enclosing" or "touching")
  3982. try:
  3983. if event.button == 1: # left click
  3984. if self.doubleclick is True:
  3985. self.doubleclick = False
  3986. if self.collection.get_selected():
  3987. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3988. if self.ui.splitter.sizes()[0] == 0:
  3989. self.ui.splitter.setSizes([1, 1])
  3990. # delete the selection shape(S) as it may be in the way
  3991. self.delete_selection_shape()
  3992. self.delete_hover_shape()
  3993. else:
  3994. if self.selection_type is not None:
  3995. self.selection_area_handler(self.pos, pos, self.selection_type)
  3996. self.selection_type = None
  3997. else:
  3998. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3999. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  4000. # and if it's not selected then it will be selected
  4001. if modifiers == QtCore.Qt.ControlModifier:
  4002. # If there is no active command (self.command_active is None) then we check if we clicked on
  4003. # a object by checking the bounding limits against mouse click position
  4004. if self.command_active is None:
  4005. self.select_objects(key='CTRL')
  4006. self.delete_hover_shape()
  4007. else:
  4008. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  4009. # checking the bounding limits against mouse click position
  4010. if self.command_active is None:
  4011. self.select_objects()
  4012. self.delete_hover_shape()
  4013. except Exception as e:
  4014. log.warning("Error: %s" % str(e))
  4015. return
  4016. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4017. """
  4018. :param start_pos: mouse position when the selection LMB click was done
  4019. :param end_pos: mouse position when the left mouse button is released
  4020. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4021. :return:
  4022. """
  4023. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4024. self.delete_selection_shape()
  4025. for obj in self.collection.get_list():
  4026. try:
  4027. # select the object(s) only if it is enabled (plotted)
  4028. if obj.options['plot']:
  4029. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4030. (obj.options['xmax'], obj.options['ymin']),
  4031. (obj.options['xmax'], obj.options['ymax']),
  4032. (obj.options['xmin'], obj.options['ymax'])])
  4033. if sel_type is True:
  4034. if poly_obj.within(poly_selection):
  4035. # create the selection box around the selected object
  4036. self.draw_selection_shape(obj)
  4037. self.collection.set_active(obj.options['name'])
  4038. else:
  4039. if poly_selection.intersects(poly_obj):
  4040. # create the selection box around the selected object
  4041. self.draw_selection_shape(obj)
  4042. self.collection.set_active(obj.options['name'])
  4043. except:
  4044. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4045. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4046. # In this case poly_obj creation (see above) will fail
  4047. pass
  4048. def select_objects(self, key=None):
  4049. # list where we store the overlapped objects under our mouse left click position
  4050. objects_under_the_click_list = []
  4051. # Populate the list with the overlapped objects on the click position
  4052. curr_x, curr_y = self.pos
  4053. for obj in self.all_objects_list:
  4054. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4055. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4056. if obj.options['name'] not in objects_under_the_click_list:
  4057. if obj.options['plot']:
  4058. # add objects to the objects_under_the_click list only if the object is plotted
  4059. # (active and not disabled)
  4060. objects_under_the_click_list.append(obj.options['name'])
  4061. try:
  4062. # If there is no element in the overlapped objects list then make everyone inactive
  4063. # because we selected "nothing"
  4064. if not objects_under_the_click_list:
  4065. self.collection.set_all_inactive()
  4066. # delete the possible selection box around a possible selected object
  4067. self.delete_selection_shape()
  4068. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4069. # only when working on App
  4070. if self.call_source == 'app':
  4071. if self.click_noproject is False:
  4072. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4073. else:
  4074. # restore auto open the Project Tab
  4075. self.click_noproject = False
  4076. # delete any text in the status bar, implicitly the last object name that was selected
  4077. self.inform.emit("")
  4078. else:
  4079. self.call_source = 'app'
  4080. else:
  4081. # case when there is only an object under the click and we toggle it
  4082. if len(objects_under_the_click_list) == 1:
  4083. if self.collection.get_active() is None :
  4084. self.collection.set_active(objects_under_the_click_list[0])
  4085. # create the selection box around the selected object
  4086. curr_sel_obj = self.collection.get_active()
  4087. self.draw_selection_shape(curr_sel_obj)
  4088. # self.inform.emit('[selected] %s: %s selected' %
  4089. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4090. if curr_sel_obj.kind == 'gerber':
  4091. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4092. color='green', name=str(curr_sel_obj.options['name'])))
  4093. elif curr_sel_obj.kind == 'excellon':
  4094. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4095. color='brown', name=str(curr_sel_obj.options['name'])))
  4096. elif curr_sel_obj.kind == 'cncjob':
  4097. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4098. color='blue', name=str(curr_sel_obj.options['name'])))
  4099. elif curr_sel_obj.kind == 'geometry':
  4100. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4101. color='red', name=str(curr_sel_obj.options['name'])))
  4102. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4103. self.collection.set_all_inactive()
  4104. self.delete_selection_shape()
  4105. self.collection.set_active(objects_under_the_click_list[0])
  4106. # create the selection box around the selected object
  4107. curr_sel_obj = self.collection.get_active()
  4108. self.draw_selection_shape(curr_sel_obj)
  4109. # self.inform.emit('[selected] %s: %s selected' %
  4110. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4111. if curr_sel_obj.kind == 'gerber':
  4112. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4113. color='green', name=str(curr_sel_obj.options['name'])))
  4114. elif curr_sel_obj.kind == 'excellon':
  4115. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4116. color='brown', name=str(curr_sel_obj.options['name'])))
  4117. elif curr_sel_obj.kind == 'cncjob':
  4118. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4119. color='blue', name=str(curr_sel_obj.options['name'])))
  4120. elif curr_sel_obj.kind == 'geometry':
  4121. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4122. color='red', name=str(curr_sel_obj.options['name'])))
  4123. else:
  4124. self.collection.set_all_inactive()
  4125. self.delete_selection_shape()
  4126. if self.call_source == 'app':
  4127. # delete any text in the status bar, implicitly the last object name that was selected
  4128. self.inform.emit("")
  4129. else:
  4130. self.call_source = 'app'
  4131. else:
  4132. # If there is no selected object
  4133. # make active the first element of the overlapped objects list
  4134. if self.collection.get_active() is None:
  4135. self.collection.set_active(objects_under_the_click_list[0])
  4136. name_sel_obj = self.collection.get_active().options['name']
  4137. # In case that there is a selected object but it is not in the overlapped object list
  4138. # make that object inactive and activate the first element in the overlapped object list
  4139. if name_sel_obj not in objects_under_the_click_list:
  4140. self.collection.set_inactive(name_sel_obj)
  4141. name_sel_obj = objects_under_the_click_list[0]
  4142. self.collection.set_active(name_sel_obj)
  4143. else:
  4144. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4145. self.collection.set_all_inactive()
  4146. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4147. len(objects_under_the_click_list)])
  4148. curr_sel_obj = self.collection.get_active()
  4149. # delete the possible selection box around a possible selected object
  4150. self.delete_selection_shape()
  4151. # create the selection box around the selected object
  4152. self.draw_selection_shape(curr_sel_obj)
  4153. # self.inform.emit('[selected] %s: %s selected' %
  4154. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4155. if curr_sel_obj.kind == 'gerber':
  4156. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4157. color='green', name=str(curr_sel_obj.options['name'])))
  4158. elif curr_sel_obj.kind == 'excellon':
  4159. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4160. color='brown', name=str(curr_sel_obj.options['name'])))
  4161. elif curr_sel_obj.kind == 'cncjob':
  4162. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4163. color='blue', name=str(curr_sel_obj.options['name'])))
  4164. elif curr_sel_obj.kind == 'geometry':
  4165. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4166. color='red', name=str(curr_sel_obj.options['name'])))
  4167. # for obj in self.collection.get_list():
  4168. # obj.plot()
  4169. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4170. # TODO: on selected objects change the object colors and do not draw the selection box
  4171. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4172. except Exception as e:
  4173. log.error("[ERROR] Something went bad. %s" % str(e))
  4174. return
  4175. def delete_hover_shape(self):
  4176. self.hover_shapes.clear()
  4177. self.hover_shapes.redraw()
  4178. def draw_hover_shape(self, sel_obj, color=None):
  4179. """
  4180. :param sel_obj: the object for which the hover shape must be drawn
  4181. :return:
  4182. """
  4183. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4184. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4185. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4186. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4187. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4188. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4189. hover_rect = hover_rect.buffer(-0.1)
  4190. hover_rect = hover_rect.buffer(0.2)
  4191. else:
  4192. hover_rect = hover_rect.buffer(-0.00393)
  4193. hover_rect = hover_rect.buffer(0.00787)
  4194. if color:
  4195. face = Color(color)
  4196. face.alpha = 0.2
  4197. outline = Color(color, alpha=0.8)
  4198. else:
  4199. face = Color(self.defaults['global_sel_fill'])
  4200. face.alpha = 0.2
  4201. outline = self.defaults['global_sel_line']
  4202. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4203. def delete_selection_shape(self):
  4204. self.move_tool.sel_shapes.clear()
  4205. self.move_tool.sel_shapes.redraw()
  4206. def draw_selection_shape(self, sel_obj, color=None):
  4207. """
  4208. :param sel_obj: the object for which the selection shape must be drawn
  4209. :return:
  4210. """
  4211. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4212. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4213. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4214. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4215. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4216. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4217. sel_rect = sel_rect.buffer(-0.1)
  4218. sel_rect = sel_rect.buffer(0.2)
  4219. else:
  4220. sel_rect = sel_rect.buffer(-0.00393)
  4221. sel_rect = sel_rect.buffer(0.00787)
  4222. if color:
  4223. face = Color(color, alpha=0.2)
  4224. outline = Color(color, alpha=0.8)
  4225. else:
  4226. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4227. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4228. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4229. face_color=face, update=True, layer=0, tolerance=None))
  4230. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4231. """
  4232. :param old_coords: old coordinates
  4233. :param coords: new coordinates
  4234. :return:
  4235. """
  4236. if 'color' in kwargs:
  4237. color = kwargs['color']
  4238. else:
  4239. color = self.defaults['global_sel_line']
  4240. if 'face_color' in kwargs:
  4241. face_color = kwargs['face_color']
  4242. else:
  4243. face_color = self.defaults['global_sel_fill']
  4244. x0, y0 = old_coords
  4245. x1, y1 = coords
  4246. pt1 = (x0, y0)
  4247. pt2 = (x1, y0)
  4248. pt3 = (x1, y1)
  4249. pt4 = (x0, y1)
  4250. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4251. color_t = Color(face_color)
  4252. color_t.alpha = 0.3
  4253. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4254. layer=0, tolerance=None)
  4255. def on_file_new_click(self):
  4256. if self.collection.get_list() and self.should_we_save:
  4257. msgbox = QtWidgets.QMessageBox()
  4258. # msgbox.setText("<B>Save changes ...</B>")
  4259. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4260. "Creating a New project will delete them.\n"
  4261. "Do you want to Save the project?"))
  4262. msgbox.setWindowTitle(_("Save changes"))
  4263. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4264. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  4265. QtWidgets.QMessageBox.No)
  4266. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4267. response = msgbox.exec_()
  4268. if response == QtWidgets.QMessageBox.Yes:
  4269. self.on_file_saveprojectas()
  4270. elif response == QtWidgets.QMessageBox.Cancel:
  4271. return
  4272. self.on_file_new()
  4273. else:
  4274. self.on_file_new()
  4275. self.inform.emit(_("[success] New Project created..."))
  4276. def on_file_new(self):
  4277. """
  4278. Callback for menu item File->New. Returns the application to its
  4279. startup state. This method is thread-safe.
  4280. :return: None
  4281. """
  4282. self.report_usage("on_file_new")
  4283. # Remove everything from memory
  4284. App.log.debug("on_file_new()")
  4285. # Clear pool
  4286. self.clear_pool()
  4287. #delete shapes left drawn from mark shape_collections, if any
  4288. for obj in self.collection.get_list():
  4289. try:
  4290. obj.mark_shapes.enabled = False
  4291. obj.mark_shapes.clear(update=True)
  4292. except:
  4293. pass
  4294. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4295. self.init_tcl()
  4296. self.delete_selection_shape()
  4297. self.collection.delete_all()
  4298. self.setup_component_editor()
  4299. # Clear project filename
  4300. self.project_filename = None
  4301. # Load the application defaults
  4302. self.load_defaults(filename='current_defaults')
  4303. # Re-fresh project options
  4304. self.on_options_app2project()
  4305. # Init Tools
  4306. self.init_tools()
  4307. # Close any Tabs opened in the Plot Tab Area section
  4308. for index in range(self.ui.plot_tab_area.count()):
  4309. self.ui.plot_tab_area.closeTab(index)
  4310. # for whatever reason previous command does not close the last tab so I do it manually
  4311. self.ui.plot_tab_area.closeTab(0)
  4312. # # And then add again the Plot Area
  4313. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4314. self.ui.plot_tab_area.protectTab(0)
  4315. # take the focus of the Notebook on Project Tab.
  4316. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4317. def obj_properties(self):
  4318. self.report_usage("obj_properties()")
  4319. self.properties_tool.run(toggle=False)
  4320. def on_project_context_save(self):
  4321. obj = self.collection.get_active()
  4322. if type(obj) == FlatCAMGeometry:
  4323. self.on_file_exportdxf()
  4324. elif type(obj) == FlatCAMExcellon:
  4325. self.on_file_saveexcellon()
  4326. elif type(obj) == FlatCAMCNCjob:
  4327. obj.on_exportgcode_button_click()
  4328. elif type(obj) == FlatCAMGerber:
  4329. self.on_file_savegerber()
  4330. def on_view_source(self):
  4331. try:
  4332. obj = self.collection.get_active()
  4333. except:
  4334. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  4335. return 'fail'
  4336. # then append the text from GCode to the text editor
  4337. try:
  4338. file = StringIO(obj.source_file)
  4339. except AttributeError:
  4340. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  4341. return 'fail'
  4342. # add the tab if it was closed
  4343. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  4344. # first clear previous text in text editor (if any)
  4345. self.ui.code_editor.clear()
  4346. # Switch plot_area to CNCJob tab
  4347. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  4348. try:
  4349. for line in file:
  4350. proc_line = str(line).strip('\n')
  4351. self.ui.code_editor.append(proc_line)
  4352. except Exception as e:
  4353. log.debug('App.on_view_source() -->%s' % str(e))
  4354. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  4355. return
  4356. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4357. self.handleTextChanged()
  4358. self.ui.show()
  4359. # if type(obj) == FlatCAMGerber:
  4360. # self.on_file_exportdxf()
  4361. # elif type(obj) == FlatCAMExcellon:
  4362. # self.on_file_exportexcellon()
  4363. def obj_move(self):
  4364. self.report_usage("obj_move()")
  4365. self.move_tool.run()
  4366. def on_fileopengerber(self):
  4367. """
  4368. File menu callback for opening a Gerber.
  4369. :return: None
  4370. """
  4371. self.report_usage("on_fileopengerber")
  4372. App.log.debug("on_fileopengerber()")
  4373. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4374. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4375. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  4376. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4377. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4378. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4379. "Allegro Files (*.art);;" \
  4380. "Mentor Files (*.pho *.gdo);;" \
  4381. "All Files (*.*)"
  4382. try:
  4383. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4384. directory=self.get_last_folder(), filter=_filter_)
  4385. except TypeError:
  4386. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4387. filenames = [str(filename) for filename in filenames]
  4388. if len(filenames) == 0:
  4389. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4390. else:
  4391. for filename in filenames:
  4392. if filename != '':
  4393. self.worker_task.emit({'fcn': self.open_gerber,
  4394. 'params': [filename]})
  4395. def on_fileopenexcellon(self):
  4396. """
  4397. File menu callback for opening an Excellon file.
  4398. :return: None
  4399. """
  4400. self.report_usage("on_fileopenexcellon")
  4401. App.log.debug("on_fileopenexcellon()")
  4402. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4403. "All Files (*.*)"
  4404. try:
  4405. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  4406. directory=self.get_last_folder(), filter=_filter_)
  4407. except TypeError:
  4408. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  4409. filenames = [str(filename) for filename in filenames]
  4410. if len(filenames) == 0:
  4411. self.inform.emit(_("[WARNING_NOTCL]Open Excellon cancelled."))
  4412. else:
  4413. for filename in filenames:
  4414. if filename != '':
  4415. self.worker_task.emit({'fcn': self.open_excellon,
  4416. 'params': [filename]})
  4417. def on_fileopengcode(self):
  4418. """
  4419. File menu call back for opening gcode.
  4420. :return: None
  4421. """
  4422. self.report_usage("on_fileopengcode")
  4423. App.log.debug("on_fileopengcode()")
  4424. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4425. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4426. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4427. "All Files (*.*)"
  4428. try:
  4429. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  4430. directory=self.get_last_folder(), filter=_filter_)
  4431. except TypeError:
  4432. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  4433. filenames = [str(filename) for filename in filenames]
  4434. if len(filenames) == 0:
  4435. self.inform.emit(_("[WARNING_NOTCL]Open G-Code cancelled."))
  4436. else:
  4437. for filename in filenames:
  4438. if filename != '':
  4439. self.worker_task.emit({'fcn': self.open_gcode,
  4440. 'params': [filename]})
  4441. def on_file_openproject(self):
  4442. """
  4443. File menu callback for opening a project.
  4444. :return: None
  4445. """
  4446. self.report_usage("on_file_openproject")
  4447. App.log.debug("on_file_openproject()")
  4448. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4449. try:
  4450. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  4451. directory=self.get_last_folder(), filter=_filter_)
  4452. except TypeError:
  4453. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  4454. # The Qt methods above will return a QString which can cause problems later.
  4455. # So far json.dump() will fail to serialize it.
  4456. # TODO: Improve the serialization methods and remove this fix.
  4457. filename = str(filename)
  4458. if filename == "":
  4459. self.inform.emit(_("[WARNING_NOTCL]Open Project cancelled."))
  4460. else:
  4461. # self.worker_task.emit({'fcn': self.open_project,
  4462. # 'params': [filename]})
  4463. # The above was failing because open_project() is not
  4464. # thread safe. The new_project()
  4465. self.open_project(filename)
  4466. def on_file_openconfig(self):
  4467. """
  4468. File menu callback for opening a config file.
  4469. :return: None
  4470. """
  4471. self.report_usage("on_file_openconfig")
  4472. App.log.debug("on_file_openconfig()")
  4473. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  4474. try:
  4475. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4476. directory=self.data_path, filter=_filter_)
  4477. except TypeError:
  4478. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4479. filter = _filter_)
  4480. if filename == "":
  4481. self.inform.emit(_("[WARNING_NOTCL]Open Config cancelled."))
  4482. else:
  4483. self.open_config_file(filename)
  4484. def on_file_exportsvg(self):
  4485. """
  4486. Callback for menu item File->Export SVG.
  4487. :return: None
  4488. """
  4489. self.report_usage("on_file_exportsvg")
  4490. App.log.debug("on_file_exportsvg()")
  4491. obj = self.collection.get_active()
  4492. if obj is None:
  4493. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4494. msg = _("Please Select a Geometry object to export")
  4495. msgbox = QtWidgets.QMessageBox()
  4496. msgbox.setInformativeText(msg)
  4497. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4498. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4499. msgbox.exec_()
  4500. return
  4501. # Check for more compatible types and add as required
  4502. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4503. and not isinstance(obj, FlatCAMExcellon)):
  4504. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  4505. msgbox = QtWidgets.QMessageBox()
  4506. msgbox.setInformativeText(msg)
  4507. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4508. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4509. msgbox.exec_()
  4510. return
  4511. name = self.collection.get_active().options["name"]
  4512. filter = "SVG File (*.svg);;All Files (*.*)"
  4513. try:
  4514. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4515. caption=_("Export SVG"),
  4516. directory=self.get_last_save_folder() + '/' + str(name),
  4517. filter=filter)
  4518. except TypeError:
  4519. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  4520. filename = str(filename)
  4521. if filename == "":
  4522. self.inform.emit(_("[WARNING_NOTCL]Export SVG cancelled."))
  4523. return
  4524. else:
  4525. self.export_svg(name, filename)
  4526. self.file_saved.emit("SVG", filename)
  4527. def on_file_exportpng(self):
  4528. self.report_usage("on_file_exportpng")
  4529. App.log.debug("on_file_exportpng()")
  4530. image = _screenshot()
  4531. data = np.asarray(image)
  4532. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4533. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  4534. return
  4535. filter_ = "PNG File (*.png);;All Files (*.*)"
  4536. try:
  4537. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4538. caption=_("Export PNG Image"),
  4539. directory=self.get_last_save_folder() + '/png_' + str(self.date).replace('-', ''),
  4540. filter=filter_)
  4541. except TypeError:
  4542. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  4543. filename = str(filename)
  4544. if filename == "":
  4545. self.inform.emit(_("Export PNG cancelled."))
  4546. return
  4547. else:
  4548. write_png(filename, data)
  4549. self.file_saved.emit("png", filename)
  4550. def on_file_savegerber(self):
  4551. """
  4552. Callback for menu item File->Export Gerber.
  4553. :return: None
  4554. """
  4555. self.report_usage("on_file_savegerber")
  4556. App.log.debug("on_file_savegerber()")
  4557. obj = self.collection.get_active()
  4558. if obj is None:
  4559. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  4560. return
  4561. # Check for more compatible types and add as required
  4562. if not isinstance(obj, FlatCAMGerber):
  4563. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  4564. return
  4565. name = self.collection.get_active().options["name"]
  4566. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  4567. try:
  4568. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4569. caption="Save Gerber source file",
  4570. directory=self.get_last_save_folder() + '/' + name,
  4571. filter=filter)
  4572. except TypeError:
  4573. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  4574. filename = str(filename)
  4575. if filename == "":
  4576. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  4577. return
  4578. else:
  4579. self.save_source_file(name, filename)
  4580. self.file_saved.emit("Gerber", filename)
  4581. def on_file_saveexcellon(self):
  4582. """
  4583. Callback for menu item File->Export Gerber.
  4584. :return: None
  4585. """
  4586. self.report_usage("on_file_saveexcellon")
  4587. App.log.debug("on_file_saveexcellon()")
  4588. obj = self.collection.get_active()
  4589. if obj is None:
  4590. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  4591. return
  4592. # Check for more compatible types and add as required
  4593. if not isinstance(obj, FlatCAMExcellon):
  4594. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4595. return
  4596. name = self.collection.get_active().options["name"]
  4597. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4598. try:
  4599. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4600. caption=_("Save Excellon source file"),
  4601. directory=self.get_last_save_folder() + '/' + name,
  4602. filter=filter)
  4603. except TypeError:
  4604. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  4605. filename = str(filename)
  4606. if filename == "":
  4607. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  4608. return
  4609. else:
  4610. self.save_source_file(name, filename)
  4611. self.file_saved.emit("Excellon", filename)
  4612. def on_file_exportexcellon(self):
  4613. """
  4614. Callback for menu item File->Export SVG.
  4615. :return: None
  4616. """
  4617. self.report_usage("on_file_exportexcellon")
  4618. App.log.debug("on_file_exportexcellon()")
  4619. obj = self.collection.get_active()
  4620. if obj is None:
  4621. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  4622. return
  4623. # Check for more compatible types and add as required
  4624. if not isinstance(obj, FlatCAMExcellon):
  4625. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4626. return
  4627. name = self.collection.get_active().options["name"]
  4628. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4629. try:
  4630. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4631. caption=_("Export Excellon"),
  4632. directory=self.get_last_save_folder() + '/' + name,
  4633. filter=filter)
  4634. except TypeError:
  4635. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  4636. filename = str(filename)
  4637. if filename == "":
  4638. self.inform.emit(_("[WARNING_NOTCL]Export Excellon cancelled."))
  4639. return
  4640. else:
  4641. self.export_excellon(name, filename)
  4642. self.file_saved.emit("Excellon", filename)
  4643. def on_file_exportdxf(self):
  4644. """
  4645. Callback for menu item File->Export DXF.
  4646. :return: None
  4647. """
  4648. self.report_usage("on_file_exportdxf")
  4649. App.log.debug("on_file_exportdxf()")
  4650. obj = self.collection.get_active()
  4651. if obj is None:
  4652. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4653. msg = _("Please Select a Geometry object to export")
  4654. msgbox = QtWidgets.QMessageBox()
  4655. msgbox.setInformativeText(msg)
  4656. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4657. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4658. msgbox.exec_()
  4659. return
  4660. # Check for more compatible types and add as required
  4661. if not isinstance(obj, FlatCAMGeometry):
  4662. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  4663. msgbox = QtWidgets.QMessageBox()
  4664. msgbox.setInformativeText(msg)
  4665. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4666. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4667. msgbox.exec_()
  4668. return
  4669. name = self.collection.get_active().options["name"]
  4670. filter = "DXF File (*.DXF);;All Files (*.*)"
  4671. try:
  4672. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4673. caption=_("Export DXF"),
  4674. directory=self.get_last_save_folder() + '/' + name,
  4675. filter=filter)
  4676. except TypeError:
  4677. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"), filter=filter)
  4678. filename = str(filename)
  4679. if filename == "":
  4680. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  4681. return
  4682. else:
  4683. self.export_dxf(name, filename)
  4684. self.file_saved.emit("DXF", filename)
  4685. def on_file_importsvg(self, type_of_obj):
  4686. """
  4687. Callback for menu item File->Import SVG.
  4688. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4689. :type type_of_obj: str
  4690. :return: None
  4691. """
  4692. self.report_usage("on_file_importsvg")
  4693. App.log.debug("on_file_importsvg()")
  4694. filter = "SVG File (*.svg);;All Files (*.*)"
  4695. try:
  4696. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  4697. directory=self.get_last_folder(), filter=filter)
  4698. except TypeError:
  4699. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"), filter=filter)
  4700. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4701. type_of_obj = "geometry"
  4702. filenames = [str(filename) for filename in filenames]
  4703. if len(filenames) == 0:
  4704. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  4705. else:
  4706. for filename in filenames:
  4707. if filename != '':
  4708. self.worker_task.emit({'fcn': self.import_svg,
  4709. 'params': [filename, type_of_obj]})
  4710. def on_file_importdxf(self, type_of_obj):
  4711. """
  4712. Callback for menu item File->Import DXF.
  4713. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4714. :type type_of_obj: str
  4715. :return: None
  4716. """
  4717. self.report_usage("on_file_importdxf")
  4718. App.log.debug("on_file_importdxf()")
  4719. filter = "DXF File (*.DXF);;All Files (*.*)"
  4720. try:
  4721. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  4722. directory=self.get_last_folder(), filter=filter)
  4723. except TypeError:
  4724. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"), filter=filter)
  4725. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4726. type_of_obj = "geometry"
  4727. filenames = [str(filename) for filename in filenames]
  4728. if len(filenames) == 0:
  4729. self.inform.emit(_("[WARNING_NOTCL]Open DXF cancelled."))
  4730. else:
  4731. for filename in filenames:
  4732. if filename != '':
  4733. self.worker_task.emit({'fcn': self.import_dxf,
  4734. 'params': [filename, type_of_obj]})
  4735. def on_filerunscript(self):
  4736. """
  4737. File menu callback for loading and running a TCL script.
  4738. :return: None
  4739. """
  4740. self.report_usage("on_filerunscript")
  4741. App.log.debug("on_file_runscript()")
  4742. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4743. try:
  4744. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  4745. directory=self.get_last_folder(), filter=_filter_)
  4746. except TypeError:
  4747. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  4748. # The Qt methods above will return a QString which can cause problems later.
  4749. # So far json.dump() will fail to serialize it.
  4750. # TODO: Improve the serialization methods and remove this fix.
  4751. filename = str(filename)
  4752. if filename == "":
  4753. self.inform.emit(_("[WARNING_NOTCL]Open TCL script cancelled."))
  4754. else:
  4755. try:
  4756. with open(filename, "r") as tcl_script:
  4757. cmd_line_shellfile_content = tcl_script.read()
  4758. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  4759. except Exception as ext:
  4760. print("ERROR: ", ext)
  4761. sys.exit(2)
  4762. def on_file_saveproject(self):
  4763. """
  4764. Callback for menu item File->Save Project. Saves the project to
  4765. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4766. if set to None. The project is saved by calling ``self.save_project()``.
  4767. :return: None
  4768. """
  4769. self.report_usage("on_file_saveproject")
  4770. if self.project_filename is None:
  4771. self.on_file_saveprojectas()
  4772. else:
  4773. self.worker_task.emit({'fcn': self.save_project,
  4774. 'params': [self.project_filename]})
  4775. # self.save_project(self.project_filename)
  4776. self.file_opened.emit("project", self.project_filename)
  4777. self.file_saved.emit("project", self.project_filename)
  4778. self.should_we_save = False
  4779. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4780. """
  4781. Callback for menu item File->Save Project As... Opens a file
  4782. chooser and saves the project to the given file via
  4783. ``self.save_project()``.
  4784. :return: None
  4785. """
  4786. self.report_usage("on_file_saveprojectas")
  4787. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4788. try:
  4789. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4790. caption=_("Save Project As ..."),
  4791. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=str(self.date.replace('-', ''))),
  4792. filter=filter_)
  4793. except TypeError:
  4794. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  4795. filename = str(filename)
  4796. if filename == '':
  4797. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  4798. return
  4799. try:
  4800. f = open(filename, 'r')
  4801. f.close()
  4802. exists = True
  4803. except IOError:
  4804. exists = False
  4805. if thread is True:
  4806. self.worker_task.emit({'fcn': self.save_project,
  4807. 'params': [filename]})
  4808. else:
  4809. self.save_project(filename)
  4810. # self.save_project(filename)
  4811. self.file_opened.emit("project", filename)
  4812. self.file_saved.emit("project", filename)
  4813. if not make_copy:
  4814. self.project_filename = filename
  4815. self.should_we_save = False
  4816. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4817. """
  4818. Exports a Geometry Object to an SVG file.
  4819. :param filename: Path to the SVG file to save to.
  4820. :return:
  4821. """
  4822. self.report_usage("export_svg()")
  4823. if filename is None:
  4824. filename = self.defaults["global_last_save_folder"]
  4825. self.log.debug("export_svg()")
  4826. try:
  4827. obj = self.collection.get_by_name(str(obj_name))
  4828. except:
  4829. # TODO: The return behavior has not been established... should raise exception?
  4830. return "Could not retrieve object: %s" % obj_name
  4831. with self.proc_container.new(_("Exporting SVG")) as proc:
  4832. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4833. # Determine bounding area for svg export
  4834. bounds = obj.bounds()
  4835. size = obj.size()
  4836. # Convert everything to strings for use in the xml doc
  4837. svgwidth = str(size[0])
  4838. svgheight = str(size[1])
  4839. minx = str(bounds[0])
  4840. miny = str(bounds[1] - size[1])
  4841. uom = obj.units.lower()
  4842. # Add a SVG Header and footer to the svg output from shapely
  4843. # The transform flips the Y Axis so that everything renders
  4844. # properly within svg apps such as inkscape
  4845. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4846. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4847. svg_header += 'width="' + svgwidth + uom + '" '
  4848. svg_header += 'height="' + svgheight + uom + '" '
  4849. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4850. svg_header += '<g transform="scale(1,-1)">'
  4851. svg_footer = '</g> </svg>'
  4852. svg_elem = svg_header + exported_svg + svg_footer
  4853. # Parse the xml through a xml parser just to add line feeds
  4854. # and to make it look more pretty for the output
  4855. svgcode = parse_xml_string(svg_elem)
  4856. with open(filename, 'w') as fp:
  4857. fp.write(svgcode.toprettyxml())
  4858. self.file_saved.emit("SVG", filename)
  4859. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  4860. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4861. """
  4862. Exports a Geometry Object to an SVG file in negative.
  4863. :param filename: Path to the SVG file to save to.
  4864. :param: use_thread: If True use threads
  4865. :type: Bool
  4866. :return:
  4867. """
  4868. self.report_usage("export_negative()")
  4869. if filename is None:
  4870. filename = self.defaults["global_last_save_folder"]
  4871. self.log.debug("export_svg() negative")
  4872. try:
  4873. obj = self.collection.get_by_name(str(obj_name))
  4874. except:
  4875. # TODO: The return behavior has not been established... should raise exception?
  4876. return "Could not retrieve object: %s" % obj_name
  4877. try:
  4878. box = self.collection.get_by_name(str(box_name))
  4879. except:
  4880. # TODO: The return behavior has not been established... should raise exception?
  4881. return "Could not retrieve object: %s" % box_name
  4882. if box is None:
  4883. self.inform.emit(_("[WARNING_NOTCL]No object Box. Using instead %s") % obj)
  4884. box = obj
  4885. def make_negative_film():
  4886. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4887. self.progress.emit(40)
  4888. # Determine bounding area for svg export
  4889. bounds = box.bounds()
  4890. size = box.size()
  4891. uom = obj.units.lower()
  4892. # Convert everything to strings for use in the xml doc
  4893. svgwidth = str(size[0] + (2 * boundary))
  4894. svgheight = str(size[1] + (2 * boundary))
  4895. minx = str(bounds[0] - boundary)
  4896. miny = str(bounds[1] + boundary + size[1])
  4897. miny_rect = str(bounds[1] - boundary)
  4898. # Add a SVG Header and footer to the svg output from shapely
  4899. # The transform flips the Y Axis so that everything renders
  4900. # properly within svg apps such as inkscape
  4901. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4902. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4903. svg_header += 'width="' + svgwidth + uom + '" '
  4904. svg_header += 'height="' + svgheight + uom + '" '
  4905. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4906. svg_header += '>'
  4907. svg_header += '<g transform="scale(1,-1)">'
  4908. svg_footer = '</g> </svg>'
  4909. self.progress.emit(60)
  4910. # Change the attributes of the exported SVG
  4911. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4912. # We set opacity to maximum
  4913. # We set the color to WHITE
  4914. root = ET.fromstring(exported_svg)
  4915. for child in root:
  4916. child.set('fill', '#FFFFFF')
  4917. child.set('opacity', '1.0')
  4918. child.set('stroke', '#FFFFFF')
  4919. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4920. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4921. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4922. first_svg_elem_tag = 'rect'
  4923. first_svg_elem_attribs = {
  4924. 'x': minx,
  4925. 'y': miny_rect,
  4926. 'width': svgwidth,
  4927. 'height': svgheight,
  4928. 'id': 'neg_rect',
  4929. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4930. }
  4931. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4932. exported_svg = ET.tostring(root)
  4933. svg_elem = svg_header + str(exported_svg) + svg_footer
  4934. self.progress.emit(80)
  4935. # Parse the xml through a xml parser just to add line feeds
  4936. # and to make it look more pretty for the output
  4937. doc = parse_xml_string(svg_elem)
  4938. with open(filename, 'w') as fp:
  4939. fp.write(doc.toprettyxml())
  4940. self.progress.emit(100)
  4941. self.file_saved.emit("SVG", filename)
  4942. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  4943. if use_thread is True:
  4944. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  4945. def job_thread_film(app_obj):
  4946. try:
  4947. make_negative_film()
  4948. except Exception as e:
  4949. proc.done()
  4950. return
  4951. proc.done()
  4952. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4953. else:
  4954. make_negative_film()
  4955. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4956. """
  4957. Exports a Geometry Object to an SVG file in negative.
  4958. :param filename: Path to the SVG file to save to.
  4959. :param: use_thread: If True use threads
  4960. :type: Bool
  4961. :return:
  4962. """
  4963. self.report_usage("export_svg_black()")
  4964. if filename is None:
  4965. filename = self.defaults["global_last_save_folder"]
  4966. self.log.debug("export_svg() black")
  4967. try:
  4968. obj = self.collection.get_by_name(str(obj_name))
  4969. except:
  4970. # TODO: The return behavior has not been established... should raise exception?
  4971. return "Could not retrieve object: %s" % obj_name
  4972. try:
  4973. box = self.collection.get_by_name(str(box_name))
  4974. except:
  4975. # TODO: The return behavior has not been established... should raise exception?
  4976. return "Could not retrieve object: %s" % box_name
  4977. if box is None:
  4978. self.inform.emit(_("[WARNING_NOTCL]No object Box. Using instead %s") % obj)
  4979. box = obj
  4980. def make_black_film():
  4981. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4982. self.progress.emit(40)
  4983. # Change the attributes of the exported SVG
  4984. # We don't need stroke-width
  4985. # We set opacity to maximum
  4986. # We set the colour to WHITE
  4987. root = ET.fromstring(exported_svg)
  4988. for child in root:
  4989. child.set('fill', '#000000')
  4990. child.set('opacity', '1.0')
  4991. child.set('stroke', '#000000')
  4992. exported_svg = ET.tostring(root)
  4993. # Determine bounding area for svg export
  4994. bounds = box.bounds()
  4995. size = box.size()
  4996. # This contain the measure units
  4997. uom = obj.units.lower()
  4998. # Define a boundary around SVG of about 1.0mm (~39mils)
  4999. if uom in "mm":
  5000. boundary = 1.0
  5001. else:
  5002. boundary = 0.0393701
  5003. self.progress.emit(80)
  5004. # Convert everything to strings for use in the xml doc
  5005. svgwidth = str(size[0] + (2 * boundary))
  5006. svgheight = str(size[1] + (2 * boundary))
  5007. minx = str(bounds[0] - boundary)
  5008. miny = str(bounds[1] + boundary + size[1])
  5009. self.log.debug(minx)
  5010. self.log.debug(miny)
  5011. # Add a SVG Header and footer to the svg output from shapely
  5012. # The transform flips the Y Axis so that everything renders
  5013. # properly within svg apps such as inkscape
  5014. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5015. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5016. svg_header += 'width="' + svgwidth + uom + '" '
  5017. svg_header += 'height="' + svgheight + uom + '" '
  5018. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5019. svg_header += '>'
  5020. svg_header += '<g transform="scale(1,-1)">'
  5021. svg_footer = '</g> </svg>'
  5022. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5023. self.progress.emit(90)
  5024. # Parse the xml through a xml parser just to add line feeds
  5025. # and to make it look more pretty for the output
  5026. doc = parse_xml_string(svg_elem)
  5027. with open(filename, 'w') as fp:
  5028. fp.write(doc.toprettyxml())
  5029. self.progress.emit(100)
  5030. self.file_saved.emit("SVG", filename)
  5031. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5032. if use_thread is True:
  5033. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5034. def job_thread_film(app_obj):
  5035. try:
  5036. make_black_film()
  5037. except Exception as e:
  5038. proc.done()
  5039. return
  5040. proc.done()
  5041. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5042. else:
  5043. make_black_film()
  5044. def save_source_file(self, obj_name, filename, use_thread=True):
  5045. """
  5046. Exports a Gerber Object to an Gerber file.
  5047. :param filename: Path to the Gerber file to save to.
  5048. :return:
  5049. """
  5050. self.report_usage("save source file()")
  5051. if filename is None:
  5052. filename = self.defaults["global_last_save_folder"]
  5053. self.log.debug("save source file()")
  5054. obj = self.collection.get_by_name(obj_name)
  5055. file_string = StringIO(obj.source_file)
  5056. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5057. with open(filename, 'w') as file:
  5058. file.writelines('G04*\n')
  5059. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5060. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5061. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5062. file.writelines('G04 Created on : %s*\n' % time_string)
  5063. for line in file_string:
  5064. file.writelines(line)
  5065. def export_excellon(self, obj_name, filename, use_thread=True):
  5066. """
  5067. Exports a Excellon Object to an Excellon file.
  5068. :param filename: Path to the Excellon file to save to.
  5069. :return:
  5070. """
  5071. self.report_usage("export_excellon()")
  5072. if filename is None:
  5073. filename = self.defaults["global_last_save_folder"]
  5074. self.log.debug("export_excellon()")
  5075. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5076. self.defaults["excellon_exp_decimals"]
  5077. )
  5078. units = ''
  5079. try:
  5080. obj = self.collection.get_by_name(str(obj_name))
  5081. except:
  5082. # TODO: The return behavior has not been established... should raise exception?
  5083. return "Could not retrieve object: %s" % obj_name
  5084. # updated units
  5085. eunits = self.defaults["excellon_exp_units"]
  5086. ewhole = self.defaults["excellon_exp_integer"]
  5087. efract = self.defaults["excellon_exp_decimals"]
  5088. ezeros = self.defaults["excellon_exp_zeros"]
  5089. eformat = self.defaults[ "excellon_exp_format"]
  5090. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5091. if fc_units == 'MM':
  5092. factor = 1 if eunits == 'METRIC' else 0.03937
  5093. else:
  5094. factor = 25.4 if eunits == 'METRIC' else 1
  5095. def make_excellon():
  5096. try:
  5097. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5098. header = 'M48\n'
  5099. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5100. (str(self.version), str(self.version_date))
  5101. header += ';Filename: %s' % str(obj_name) + '\n'
  5102. header += ';Created on : %s' % time_str + '\n'
  5103. if eformat == 'dec':
  5104. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5105. header += eunits + '\n'
  5106. for tool in obj.tools:
  5107. if eunits == 'METRIC':
  5108. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5109. tool=str(tool),
  5110. dec=2)
  5111. else:
  5112. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5113. tool=str(tool),
  5114. dec=4)
  5115. else:
  5116. if ezeros == 'LZ':
  5117. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5118. form='ndec', e_zeros='LZ', factor=factor)
  5119. header += '%s,%s\n' % (eunits, 'LZ')
  5120. header += format_exc
  5121. for tool in obj.tools:
  5122. if eunits == 'METRIC':
  5123. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5124. tool=str(tool),
  5125. dec=2)
  5126. else:
  5127. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5128. tool=str(tool),
  5129. dec=4)
  5130. else:
  5131. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5132. form='ndec', e_zeros='TZ', factor=factor)
  5133. header += '%s,%s\n' % (eunits, 'TZ')
  5134. header += format_exc
  5135. for tool in obj.tools:
  5136. if eunits == 'METRIC':
  5137. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5138. tool=str(tool),
  5139. dec=2)
  5140. else:
  5141. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5142. tool=str(tool),
  5143. dec=4)
  5144. header += '%\n'
  5145. footer = 'M30\n'
  5146. exported_excellon = header
  5147. exported_excellon += excellon_code
  5148. exported_excellon += footer
  5149. with open(filename, 'w') as fp:
  5150. fp.write(exported_excellon)
  5151. self.file_saved.emit("Excellon", filename)
  5152. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5153. except Exception as e:
  5154. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5155. return 'fail'
  5156. if use_thread is True:
  5157. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5158. def job_thread_exc(app_obj):
  5159. ret = make_excellon()
  5160. if ret == 'fail':
  5161. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5162. return
  5163. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5164. else:
  5165. ret = make_excellon()
  5166. if ret == 'fail':
  5167. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5168. return
  5169. def export_dxf(self, obj_name, filename, use_thread=True):
  5170. """
  5171. Exports a Geometry Object to an DXF file.
  5172. :param filename: Path to the DXF file to save to.
  5173. :return:
  5174. """
  5175. self.report_usage("export_dxf()")
  5176. if filename is None:
  5177. filename = self.defaults["global_last_save_folder"]
  5178. self.log.debug("export_dxf()")
  5179. format_exc = ''
  5180. units = ''
  5181. try:
  5182. obj = self.collection.get_by_name(str(obj_name))
  5183. except:
  5184. # TODO: The return behavior has not been established... should raise exception?
  5185. return "Could not retrieve object: %s" % obj_name
  5186. # updated units
  5187. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5188. if units == 'IN' or units == 'INCH':
  5189. units = 'INCH'
  5190. elif units == 'MM' or units == 'METIRC':
  5191. units ='METRIC'
  5192. def make_dxf():
  5193. try:
  5194. dxf_code = obj.export_dxf()
  5195. dxf_code.saveas(filename)
  5196. self.file_saved.emit("DXF", filename)
  5197. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  5198. except:
  5199. return 'fail'
  5200. if use_thread is True:
  5201. with self.proc_container.new(_("Exporting DXF")) as proc:
  5202. def job_thread_exc(app_obj):
  5203. ret = make_dxf()
  5204. if ret == 'fail':
  5205. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5206. return
  5207. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5208. else:
  5209. ret = make_dxf()
  5210. if ret == 'fail':
  5211. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5212. return
  5213. def import_svg(self, filename, geo_type='geometry', outname=None):
  5214. """
  5215. Adds a new Geometry Object to the projects and populates
  5216. it with shapes extracted from the SVG file.
  5217. :param filename: Path to the SVG file.
  5218. :param outname:
  5219. :return:
  5220. """
  5221. self.report_usage("import_svg()")
  5222. obj_type = ""
  5223. if geo_type is None or geo_type == "geometry":
  5224. obj_type = "geometry"
  5225. elif geo_type == "gerber":
  5226. obj_type = geo_type
  5227. else:
  5228. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5229. "Only Geometry and Gerber are supported"))
  5230. return
  5231. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5232. def obj_init(geo_obj, app_obj):
  5233. geo_obj.import_svg(filename, obj_type, units=units)
  5234. geo_obj.multigeo = False
  5235. with self.proc_container.new(_("Importing SVG")) as proc:
  5236. # Object name
  5237. name = outname or filename.split('/')[-1].split('\\')[-1]
  5238. self.new_object(obj_type, name, obj_init, autoselected=False)
  5239. self.progress.emit(20)
  5240. # Register recent file
  5241. self.file_opened.emit("svg", filename)
  5242. # GUI feedback
  5243. self.inform.emit(_("[success] Opened: %s") % filename)
  5244. self.progress.emit(100)
  5245. def import_dxf(self, filename, geo_type='geometry', outname=None):
  5246. """
  5247. Adds a new Geometry Object to the projects and populates
  5248. it with shapes extracted from the DXF file.
  5249. :param filename: Path to the DXF file.
  5250. :param outname:
  5251. :type putname: str
  5252. :return:
  5253. """
  5254. self.report_usage("import_dxf()")
  5255. obj_type = ""
  5256. if geo_type is None or geo_type == "geometry":
  5257. obj_type = "geometry"
  5258. elif geo_type == "gerber":
  5259. obj_type = geo_type
  5260. else:
  5261. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5262. "Only Geometry and Gerber are supported"))
  5263. return
  5264. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5265. def obj_init(geo_obj, app_obj):
  5266. geo_obj.import_dxf(filename, obj_type, units=units)
  5267. geo_obj.multigeo = False
  5268. with self.proc_container.new(_("Importing DXF")) as proc:
  5269. # Object name
  5270. name = outname or filename.split('/')[-1].split('\\')[-1]
  5271. self.new_object(obj_type, name, obj_init, autoselected=False)
  5272. self.progress.emit(20)
  5273. # Register recent file
  5274. self.file_opened.emit("dxf", filename)
  5275. # GUI feedback
  5276. self.inform.emit(_("[success] Opened: %s") % filename)
  5277. self.progress.emit(100)
  5278. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  5279. """
  5280. Adds a new Geometry Object to the projects and populates
  5281. it with shapes extracted from the SVG file.
  5282. :param filename: Path to the SVG file.
  5283. :param outname:
  5284. :return:
  5285. """
  5286. self.report_usage("import_image()")
  5287. obj_type = ""
  5288. if type is None or type == "geometry":
  5289. obj_type = "geometry"
  5290. elif type == "gerber":
  5291. obj_type = type
  5292. else:
  5293. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5294. "Only Geometry and Gerber are supported"))
  5295. return
  5296. def obj_init(geo_obj, app_obj):
  5297. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  5298. geo_obj.multigeo = False
  5299. with self.proc_container.new(_("Importing Image")) as proc:
  5300. # Object name
  5301. name = outname or filename.split('/')[-1].split('\\')[-1]
  5302. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  5303. self.new_object(obj_type, name, obj_init)
  5304. self.progress.emit(20)
  5305. # Register recent file
  5306. self.file_opened.emit("image", filename)
  5307. # GUI feedback
  5308. self.inform.emit(_("[success] Opened: %s") % filename)
  5309. self.progress.emit(100)
  5310. def open_gerber(self, filename, outname=None):
  5311. """
  5312. Opens a Gerber file, parses it and creates a new object for
  5313. it in the program. Thread-safe.
  5314. :param outname: Name of the resulting object. None causes the
  5315. name to be that of the file.
  5316. :param filename: Gerber file filename
  5317. :type filename: str
  5318. :param follow: If true, the parser will not create polygons, just lines
  5319. following the gerber path.
  5320. :type follow: bool
  5321. :return: None
  5322. """
  5323. # How the object should be initialized
  5324. def obj_init(gerber_obj, app_obj):
  5325. assert isinstance(gerber_obj, FlatCAMGerber), \
  5326. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  5327. # Opening the file happens here
  5328. self.progress.emit(30)
  5329. try:
  5330. gerber_obj.parse_file(filename)
  5331. except IOError:
  5332. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  5333. app_obj.progress.emit(0)
  5334. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  5335. return "fail"
  5336. except ParseError as err:
  5337. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename, error=str(err)))
  5338. app_obj.progress.emit(0)
  5339. self.log.error(str(err))
  5340. return "fail"
  5341. except:
  5342. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  5343. msg += traceback.format_exc()
  5344. app_obj.inform.emit(msg)
  5345. return "fail"
  5346. if gerber_obj.is_empty():
  5347. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  5348. # self.collection.set_active(gerber_obj.options["name"])
  5349. # self.collection.delete_active()
  5350. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  5351. return "fail"
  5352. # Further parsing
  5353. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  5354. App.log.debug("open_gerber()")
  5355. with self.proc_container.new(_("Opening Gerber")) as proc:
  5356. self.progress.emit(10)
  5357. # Object name
  5358. name = outname or filename.split('/')[-1].split('\\')[-1]
  5359. ### Object creation ###
  5360. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  5361. if ret == 'fail':
  5362. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  5363. return
  5364. # Register recent file
  5365. self.file_opened.emit("gerber", filename)
  5366. self.progress.emit(100)
  5367. # GUI feedback
  5368. self.inform.emit(_("[success] Opened: %s") % filename)
  5369. def open_excellon(self, filename, outname=None):
  5370. """
  5371. Opens an Excellon file, parses it and creates a new object for
  5372. it in the program. Thread-safe.
  5373. :param outname: Name of the resulting object. None causes the
  5374. name to be that of the file.
  5375. :param filename: Excellon file filename
  5376. :type filename: str
  5377. :return: None
  5378. """
  5379. App.log.debug("open_excellon()")
  5380. #self.progress.emit(10)
  5381. # How the object should be initialized
  5382. def obj_init(excellon_obj, app_obj):
  5383. # self.progress.emit(20)
  5384. try:
  5385. ret = excellon_obj.parse_file(filename)
  5386. if ret == "fail":
  5387. log.debug("Excellon parsing failed.")
  5388. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  5389. return "fail"
  5390. except IOError:
  5391. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  5392. log.debug("Could not open Excellon object.")
  5393. self.progress.emit(0) # TODO: self and app_bjj mixed
  5394. return "fail"
  5395. except:
  5396. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  5397. msg += traceback.format_exc()
  5398. app_obj.inform.emit(msg)
  5399. return "fail"
  5400. ret = excellon_obj.create_geometry()
  5401. if ret == 'fail':
  5402. log.debug("Could not create geometry for Excellon object.")
  5403. return "fail"
  5404. # if excellon_obj.is_empty():
  5405. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5406. # return "fail"
  5407. for tool in excellon_obj.tools:
  5408. if excellon_obj.tools[tool]['solid_geometry']:
  5409. return
  5410. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  5411. return "fail"
  5412. with self.proc_container.new(_("Opening Excellon.")):
  5413. # Object name
  5414. name = outname or filename.split('/')[-1].split('\\')[-1]
  5415. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  5416. if ret == 'fail':
  5417. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  5418. return
  5419. # Register recent file
  5420. self.file_opened.emit("excellon", filename)
  5421. # GUI feedback
  5422. self.inform.emit(_("[success] Opened: %s") % filename)
  5423. # self.progress.emit(100)
  5424. def open_gcode(self, filename, outname=None):
  5425. """
  5426. Opens a G-gcode file, parses it and creates a new object for
  5427. it in the program. Thread-safe.
  5428. :param outname: Name of the resulting object. None causes the
  5429. name to be that of the file.
  5430. :param filename: G-code file filename
  5431. :type filename: str
  5432. :return: None
  5433. """
  5434. App.log.debug("open_gcode()")
  5435. # How the object should be initialized
  5436. def obj_init(job_obj, app_obj_):
  5437. """
  5438. :type app_obj_: App
  5439. """
  5440. assert isinstance(app_obj_, App), \
  5441. "Initializer expected App, got %s" % type(app_obj_)
  5442. self.progress.emit(10)
  5443. try:
  5444. f = open(filename)
  5445. gcode = f.read()
  5446. f.close()
  5447. except IOError:
  5448. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  5449. self.progress.emit(0)
  5450. return "fail"
  5451. job_obj.gcode = gcode
  5452. self.progress.emit(20)
  5453. ret = job_obj.gcode_parse()
  5454. if ret == "fail":
  5455. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  5456. return "fail"
  5457. self.progress.emit(60)
  5458. job_obj.create_geometry()
  5459. with self.proc_container.new(_("Opening G-Code.")):
  5460. # Object name
  5461. name = outname or filename.split('/')[-1].split('\\')[-1]
  5462. # New object creation and file processing
  5463. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  5464. if ret == 'fail':
  5465. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5466. "Attempting to create a FlatCAM CNCJob Object from "
  5467. "G-Code file failed during processing"))
  5468. return "fail"
  5469. # Register recent file
  5470. self.file_opened.emit("cncjob", filename)
  5471. # GUI feedback
  5472. self.inform.emit(_("[success] Opened: %s") % filename)
  5473. self.progress.emit(100)
  5474. def open_config_file(self, filename, run_from_arg=None):
  5475. """
  5476. Loads a config file from the specified file.
  5477. :param filename: Name of the file from which to load.
  5478. :type filename: str
  5479. :return: None
  5480. """
  5481. App.log.debug("Opening config file: " + filename)
  5482. # add the tab if it was closed
  5483. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  5484. # first clear previous text in text editor (if any)
  5485. self.ui.code_editor.clear()
  5486. # Switch plot_area to CNCJob tab
  5487. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5488. try:
  5489. if filename:
  5490. f = QtCore.QFile(filename)
  5491. if f.open(QtCore.QIODevice.ReadOnly):
  5492. stream = QtCore.QTextStream(f)
  5493. gcode_edited = stream.readAll()
  5494. self.ui.code_editor.setPlainText(gcode_edited)
  5495. f.close()
  5496. except IOError:
  5497. App.log.error("Failed to open config file: %s" % filename)
  5498. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  5499. return
  5500. def open_project(self, filename, run_from_arg=None):
  5501. """
  5502. Loads a project from the specified file.
  5503. 1) Loads and parses file
  5504. 2) Registers the file as recently opened.
  5505. 3) Calls on_file_new()
  5506. 4) Updates options
  5507. 5) Calls new_object() with the object's from_dict() as init method.
  5508. 6) Calls plot_all()
  5509. :param filename: Name of the file from which to load.
  5510. :type filename: str
  5511. :return: None
  5512. """
  5513. App.log.debug("Opening project: " + filename)
  5514. # Open and parse an uncompressed Project file
  5515. try:
  5516. f = open(filename, 'r')
  5517. except IOError:
  5518. App.log.error("Failed to open project file: %s" % filename)
  5519. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  5520. return
  5521. try:
  5522. d = json.load(f, object_hook=dict2obj)
  5523. except:
  5524. App.log.error("Failed to parse project file: %s" % filename)
  5525. self.inform.emit(_("[ERROR_NOTCL] Failed to parse project file: %s") % filename)
  5526. f.close()
  5527. # Open and parse a compressed Project file
  5528. try:
  5529. with lzma.open(filename) as f:
  5530. file_content = f.read().decode('utf-8')
  5531. d = json.loads(file_content, object_hook=dict2obj)
  5532. except IOError:
  5533. App.log.error("Failed to open project file: %s" % filename)
  5534. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  5535. return
  5536. self.file_opened.emit("project", filename)
  5537. # Clear the current project
  5538. ## NOT THREAD SAFE ##
  5539. if run_from_arg is True:
  5540. pass
  5541. else:
  5542. self.on_file_new()
  5543. #Project options
  5544. self.options.update(d['options'])
  5545. self.project_filename = filename
  5546. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5547. self.set_screen_units(self.options["units"])
  5548. # Re create objects
  5549. App.log.debug("Re-creating objects...")
  5550. for obj in d['objs']:
  5551. def obj_init(obj_inst, app_inst):
  5552. obj_inst.from_dict(obj)
  5553. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  5554. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  5555. self.plot_all()
  5556. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  5557. self.should_we_save = False
  5558. App.log.debug("Project loaded")
  5559. def propagate_defaults(self, silent=False):
  5560. """
  5561. This method is used to set default values in classes. It's
  5562. an alternative to project options but allows the use
  5563. of values invisible to the user.
  5564. :return: None
  5565. """
  5566. if silent is False:
  5567. self.log.debug("propagate_defaults()")
  5568. # Which objects to update the given parameters.
  5569. routes = {
  5570. "global_zdownrate": CNCjob,
  5571. "excellon_zeros": Excellon,
  5572. "excellon_format_upper_in": Excellon,
  5573. "excellon_format_lower_in": Excellon,
  5574. "excellon_format_upper_mm": Excellon,
  5575. "excellon_format_lower_mm": Excellon,
  5576. "excellon_units": Excellon,
  5577. "gerber_use_buffer_for_union": Gerber,
  5578. "geometry_multidepth": Geometry
  5579. }
  5580. for param in routes:
  5581. if param in routes[param].defaults:
  5582. try:
  5583. routes[param].defaults[param] = self.defaults[param]
  5584. if silent is False:
  5585. self.log.debug(" " + param + " OK")
  5586. except KeyError:
  5587. if silent is False:
  5588. self.log.debug(" ERROR: " + param + " not in defaults.")
  5589. else:
  5590. # Try extracting the name:
  5591. # classname_param here is param in the object
  5592. if param.find(routes[param].__name__.lower() + "_") == 0:
  5593. p = param[len(routes[param].__name__) + 1:]
  5594. if p in routes[param].defaults:
  5595. routes[param].defaults[p] = self.defaults[param]
  5596. if silent is False:
  5597. self.log.debug(" " + param + " OK!")
  5598. def restore_main_win_geom(self):
  5599. try:
  5600. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5601. self.defaults["global_def_win_y"],
  5602. self.defaults["global_def_win_w"],
  5603. self.defaults["global_def_win_h"])
  5604. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  5605. settings = QSettings("Open Source", "FlatCAM")
  5606. if settings.contains("maximized_gui"):
  5607. maximized_ui = settings.value('maximized_gui', type=bool)
  5608. if maximized_ui is True:
  5609. self.ui.showMaximized()
  5610. except KeyError:
  5611. pass
  5612. def plot_all(self, zoom=True):
  5613. """
  5614. Re-generates all plots from all objects.
  5615. :return: None
  5616. """
  5617. self.log.debug("Plot_all()")
  5618. for obj in self.collection.get_list():
  5619. def worker_task(obj):
  5620. with self.proc_container.new("Plotting"):
  5621. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5622. if zoom:
  5623. self.object_plotted.emit(obj)
  5624. # Send to worker
  5625. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5626. # self.progress.emit(10)
  5627. #
  5628. # def worker_task(app_obj):
  5629. # print "worker task"
  5630. # percentage = 0.1
  5631. # try:
  5632. # delta = 0.9 / len(self.collection.get_list())
  5633. # except ZeroDivisionError:
  5634. # self.progress.emit(0)
  5635. # return
  5636. # for obj in self.collection.get_list():
  5637. # with self.proc_container.new("Plotting"):
  5638. # obj.plot()
  5639. # app_obj.object_plotted.emit(obj)
  5640. #
  5641. # percentage += delta
  5642. # self.progress.emit(int(percentage*100))
  5643. #
  5644. # self.progress.emit(0)
  5645. # self.plots_updated.emit()
  5646. #
  5647. # # Send to worker
  5648. # #self.worker.add_task(worker_task, [self])
  5649. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5650. def register_folder(self, filename):
  5651. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5652. def register_save_folder(self, filename):
  5653. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5654. def set_progress_bar(self, percentage, text=""):
  5655. self.ui.progress_bar.setValue(int(percentage))
  5656. def setup_shell(self):
  5657. """
  5658. Creates shell functions. Runs once at startup.
  5659. :return: None
  5660. """
  5661. self.log.debug("setup_shell()")
  5662. def shelp(p=None):
  5663. if not p:
  5664. return _("Available commands:\n") + \
  5665. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  5666. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  5667. if p not in commands:
  5668. return "Unknown command: %s" % p
  5669. return commands[p]["help"]
  5670. # --- Migrated to new architecture ---
  5671. # def options(name):
  5672. # ops = self.collection.get_by_name(str(name)).options
  5673. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  5674. def h(*args):
  5675. """
  5676. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  5677. and standalone parameters into list.
  5678. """
  5679. kwa = {}
  5680. a = []
  5681. n = len(args)
  5682. name = None
  5683. for i in range(n):
  5684. match = re.search(r'^-([a-zA-Z].*)', args[i])
  5685. if match:
  5686. assert name is None
  5687. name = match.group(1)
  5688. continue
  5689. if name is None:
  5690. a.append(args[i])
  5691. else:
  5692. kwa[name] = args[i]
  5693. name = None
  5694. return a, kwa
  5695. @contextmanager
  5696. def wait_signal(signal, timeout=10000):
  5697. """
  5698. Block loop until signal emitted, timeout (ms) elapses
  5699. or unhandled exception happens in a thread.
  5700. :param signal: Signal to wait for.
  5701. """
  5702. loop = QtCore.QEventLoop()
  5703. # Normal termination
  5704. signal.connect(loop.quit)
  5705. # Termination by exception in thread
  5706. self.thread_exception.connect(loop.quit)
  5707. status = {'timed_out': False}
  5708. def report_quit():
  5709. status['timed_out'] = True
  5710. loop.quit()
  5711. yield
  5712. # Temporarily change how exceptions are managed.
  5713. oeh = sys.excepthook
  5714. ex = []
  5715. def except_hook(type_, value, traceback_):
  5716. ex.append(value)
  5717. oeh(type_, value, traceback_)
  5718. sys.excepthook = except_hook
  5719. # Terminate on timeout
  5720. if timeout is not None:
  5721. QtCore.QTimer.singleShot(timeout, report_quit)
  5722. #### Block ####
  5723. loop.exec_()
  5724. # Restore exception management
  5725. sys.excepthook = oeh
  5726. if ex:
  5727. self.raiseTclError(str(ex[0]))
  5728. if status['timed_out']:
  5729. raise Exception('Timed out!')
  5730. def make_docs():
  5731. output = ''
  5732. import collections
  5733. od = collections.OrderedDict(sorted(commands.items()))
  5734. for cmd_, val in od.items():
  5735. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  5736. t = val['help']
  5737. usage_i = t.find('>')
  5738. if usage_i < 0:
  5739. expl = t
  5740. output += expl + '\n\n'
  5741. continue
  5742. expl = t[:usage_i - 1]
  5743. output += expl + '\n\n'
  5744. end_usage_i = t[usage_i:].find('\n')
  5745. if end_usage_i < 0:
  5746. end_usage_i = len(t[usage_i:])
  5747. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  5748. else:
  5749. extras = t[usage_i+end_usage_i+1:]
  5750. parts = [s.strip() for s in extras.split('\n')]
  5751. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  5752. for p in parts:
  5753. output += ' ' + p + '\n\n'
  5754. return output
  5755. '''
  5756. Howto implement TCL shell commands:
  5757. All parameters passed to command should be possible to set as None and test it afterwards.
  5758. This is because we need to see error caused in tcl,
  5759. if None value as default parameter is not allowed TCL will return empty error.
  5760. Use:
  5761. def mycommand(name=None,...):
  5762. Test it like this:
  5763. if name is None:
  5764. self.raise_tcl_error('Argument name is missing.')
  5765. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  5766. otherwise we will miss it and processing will silently continue.
  5767. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  5768. which is catched in exec_command and displayed in TCL shell console with red background.
  5769. Error in console is displayed with TCL trace.
  5770. This behavior works only within main thread,
  5771. errors with promissed tasks can be catched and detected only with log.
  5772. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  5773. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  5774. '''
  5775. commands = {
  5776. 'help': {
  5777. 'fcn': shelp,
  5778. 'help': _("Shows list of commands.")
  5779. },
  5780. }
  5781. # Import/overwrite tcl commands as objects of TclCommand descendants
  5782. # This modifies the variable 'commands'.
  5783. tclCommands.register_all_commands(self, commands)
  5784. # Add commands to the tcl interpreter
  5785. for cmd in commands:
  5786. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  5787. # Make the tcl puts function return instead of print to stdout
  5788. self.tcl.eval('''
  5789. rename puts original_puts
  5790. proc puts {args} {
  5791. if {[llength $args] == 1} {
  5792. return "[lindex $args 0]"
  5793. } else {
  5794. eval original_puts $args
  5795. }
  5796. }
  5797. ''')
  5798. def setup_recent_items(self):
  5799. # TODO: Move this to constructor
  5800. icons = {
  5801. "gerber": "share/flatcam_icon16.png",
  5802. "excellon": "share/drill16.png",
  5803. "cncjob": "share/cnc16.png",
  5804. "project": "share/project16.png",
  5805. "svg": "share/geometry16.png",
  5806. "dxf": "share/dxf16.png",
  5807. "image": "share/image16.png"
  5808. }
  5809. openers = {
  5810. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  5811. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  5812. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  5813. 'project': self.open_project,
  5814. 'svg': self.import_svg,
  5815. 'dxf': self.import_dxf,
  5816. 'image': self.import_image
  5817. }
  5818. # Open file
  5819. try:
  5820. f = open(self.data_path + '/recent.json')
  5821. except IOError:
  5822. App.log.error("Failed to load recent item list.")
  5823. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  5824. return
  5825. try:
  5826. self.recent = json.load(f)
  5827. except json.scanner.JSONDecodeError:
  5828. App.log.error("Failed to parse recent item list.")
  5829. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  5830. f.close()
  5831. return
  5832. f.close()
  5833. # Closure needed to create callbacks in a loop.
  5834. # Otherwise late binding occurs.
  5835. def make_callback(func, fname):
  5836. def opener():
  5837. func(fname)
  5838. return opener
  5839. def reset_recent():
  5840. # Reset menu
  5841. self.ui.recent.clear()
  5842. self.recent = []
  5843. try:
  5844. f = open(self.data_path + '/recent.json', 'w')
  5845. except IOError:
  5846. App.log.error("Failed to open recent items file for writing.")
  5847. return
  5848. json.dump(self.recent, f)
  5849. # Reset menu
  5850. self.ui.recent.clear()
  5851. # Create menu items
  5852. for recent in self.recent:
  5853. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5854. try:
  5855. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5856. # Attach callback
  5857. o = make_callback(openers[recent["kind"]], recent['filename'])
  5858. action.triggered.connect(o)
  5859. self.ui.recent.addAction(action)
  5860. except KeyError:
  5861. App.log.error("Unsupported file type: %s" % recent["kind"])
  5862. # Last action in Recent Files menu is one that Clear the content
  5863. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5864. clear_action.triggered.connect(reset_recent)
  5865. self.ui.recent.addSeparator()
  5866. self.ui.recent.addAction(clear_action)
  5867. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5868. # self.ui.menufilerecent.set_submenu(recent_menu)
  5869. # recent_menu.show_all()
  5870. # self.ui.recent.show()
  5871. self.log.debug("Recent items list has been populated.")
  5872. def setup_component_editor(self):
  5873. # label = QtWidgets.QLabel("Choose an item from Project")
  5874. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5875. sel_title = QtWidgets.QTextEdit(
  5876. _('<b>Shortcut Key List</b>'))
  5877. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5878. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5879. # font = self.sel_title.font()
  5880. # font.setPointSize(12)
  5881. # self.sel_title.setFont(font)
  5882. selected_text = _('''
  5883. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  5884. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5885. The normal flow when working in FlatCAM is the following:</span></p>
  5886. <ol>
  5887. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  5888. <br />
  5889. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  5890. &nbsp;</li>
  5891. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  5892. <br />
  5893. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  5894. <br />
  5895. You can change the parameters in this screen and the flow direction is like this:<br />
  5896. <br />
  5897. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  5898. </ol>
  5899. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  5900. ''')
  5901. sel_title.setText(selected_text)
  5902. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5903. self.ui.selected_scroll_area.setWidget(sel_title)
  5904. # tool_title = QtWidgets.QTextEdit(
  5905. # '<b>Shortcut Key List</b>')
  5906. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5907. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5908. # # font = self.sel_title.font()
  5909. # # font.setPointSize(12)
  5910. # # self.sel_title.setFont(font)
  5911. #
  5912. # tool_text = '''
  5913. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  5914. #
  5915. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5916. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  5917. #
  5918. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  5919. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  5920. #
  5921. # <ol>
  5922. # </ol>
  5923. #
  5924. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  5925. #
  5926. # '''
  5927. #
  5928. # tool_title.setText(tool_text)
  5929. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5930. #
  5931. # self.ui.tool_scroll_area.setWidget(tool_title)
  5932. def setup_obj_classes(self):
  5933. """
  5934. Sets up application specifics on the FlatCAMObj class.
  5935. :return: None
  5936. """
  5937. FlatCAMObj.app = self
  5938. ObjectCollection.app = self
  5939. FCProcess.app = self
  5940. FCProcessContainer.app = self
  5941. def version_check(self):
  5942. """
  5943. Checks for the latest version of the program. Alerts the
  5944. user if theirs is outdated. This method is meant to be run
  5945. in a separate thread.
  5946. :return: None
  5947. """
  5948. self.log.debug("version_check()")
  5949. if self.ui.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5950. full_url = App.version_url + \
  5951. "?s=" + str(self.defaults['global_serial']) + \
  5952. "&v=" + str(self.version) + \
  5953. "&os=" + str(self.os) + \
  5954. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5955. else:
  5956. # no_stats dict; just so it won't break things on website
  5957. no_ststs_dict = {}
  5958. no_ststs_dict["global_ststs"] = {}
  5959. full_url = App.version_url + \
  5960. "?s=" + str(self.defaults['global_serial']) + \
  5961. "&v=" + str(self.version) + \
  5962. "&os=" + str(self.os) + \
  5963. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5964. App.log.debug("Checking for updates @ %s" % full_url)
  5965. ### Get the data
  5966. try:
  5967. f = urllib.request.urlopen(full_url)
  5968. except:
  5969. # App.log.warning("Failed checking for latest version. Could not connect.")
  5970. self.log.warning("Failed checking for latest version. Could not connect.")
  5971. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  5972. return
  5973. try:
  5974. data = json.load(f)
  5975. except Exception as e:
  5976. App.log.error("Could not parse information about latest version.")
  5977. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  5978. App.log.debug("json.load(): %s" % str(e))
  5979. f.close()
  5980. return
  5981. f.close()
  5982. ### Latest version?
  5983. if self.version >= data["version"]:
  5984. App.log.debug("FlatCAM is up to date!")
  5985. self.inform.emit(_("[success] FlatCAM is up to date!"))
  5986. return
  5987. App.log.debug("Newer version available.")
  5988. self.message.emit(
  5989. _("Newer Version Available"),
  5990. _("There is a newer version of FlatCAM available for download:\n\n") +
  5991. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  5992. _("info")
  5993. )
  5994. def on_zoom_fit(self, event):
  5995. """
  5996. Callback for zoom-out request. This can be either from the corresponding
  5997. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5998. with axes limits from the geometry bounds of all objects.
  5999. :param event: Ignored.
  6000. :return: None
  6001. """
  6002. self.plotcanvas.fit_view()
  6003. def disable_all_plots(self):
  6004. self.report_usage("disable_all_plots()")
  6005. self.disable_plots(self.collection.get_list())
  6006. self.inform.emit(_("[success]All plots disabled."))
  6007. def disable_other_plots(self):
  6008. self.report_usage("disable_other_plots()")
  6009. self.disable_plots(self.collection.get_non_selected())
  6010. self.inform.emit(_("[success]All non selected plots disabled."))
  6011. def enable_all_plots(self):
  6012. self.report_usage("enable_all_plots()")
  6013. self.enable_plots(self.collection.get_list())
  6014. self.inform.emit(_("[success]All plots enabled."))
  6015. # TODO: FIX THIS
  6016. '''
  6017. By default this is not threaded
  6018. If threaded the app give warnings like this:
  6019. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6020. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6021. '''
  6022. def enable_plots(self, objects, threaded=False):
  6023. if threaded is True:
  6024. def worker_task(app_obj):
  6025. percentage = 0.1
  6026. try:
  6027. delta = 0.9 / len(objects)
  6028. except ZeroDivisionError:
  6029. self.progress.emit(0)
  6030. return
  6031. for obj in objects:
  6032. obj.options['plot'] = True
  6033. percentage += delta
  6034. self.progress.emit(int(percentage*100))
  6035. self.progress.emit(0)
  6036. self.plots_updated.emit()
  6037. self.collection.update_view()
  6038. # Send to worker
  6039. # self.worker.add_task(worker_task, [self])
  6040. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6041. else:
  6042. for obj in objects:
  6043. obj.options['plot'] = True
  6044. self.progress.emit(0)
  6045. self.plots_updated.emit()
  6046. self.collection.update_view()
  6047. # TODO: FIX THIS
  6048. '''
  6049. By default this is not threaded
  6050. If threaded the app give warnings like this:
  6051. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6052. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6053. '''
  6054. def disable_plots(self, objects, threaded=False):
  6055. # TODO: This method is very similar to replot_all. Try to merge.
  6056. """
  6057. Disables plots
  6058. :param objects: list
  6059. Objects to be disabled
  6060. :return:
  6061. """
  6062. if threaded is True:
  6063. self.progress.emit(10)
  6064. def worker_task(app_obj):
  6065. percentage = 0.1
  6066. try:
  6067. delta = 0.9 / len(objects)
  6068. except ZeroDivisionError:
  6069. self.progress.emit(0)
  6070. return
  6071. for obj in objects:
  6072. obj.options['plot'] = False
  6073. percentage += delta
  6074. self.progress.emit(int(percentage*100))
  6075. self.progress.emit(0)
  6076. self.plots_updated.emit()
  6077. self.collection.update_view()
  6078. # Send to worker
  6079. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6080. else:
  6081. for obj in objects:
  6082. obj.options['plot'] = False
  6083. self.plots_updated.emit()
  6084. self.collection.update_view()
  6085. def clear_plots(self):
  6086. objects = self.collection.get_list()
  6087. for obj in objects:
  6088. obj.clear(obj == objects[-1])
  6089. # Clear pool to free memory
  6090. self.clear_pool()
  6091. def generate_cnc_job(self, objects):
  6092. self.report_usage("generate_cnc_job()")
  6093. # for obj in objects:
  6094. # obj.generatecncjob()
  6095. for obj in objects:
  6096. obj.on_generatecnc_button_click()
  6097. def save_project(self, filename):
  6098. """
  6099. Saves the current project to the specified file.
  6100. :param filename: Name of the file in which to save.
  6101. :type filename: str
  6102. :return: None
  6103. """
  6104. self.log.debug("save_project()")
  6105. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6106. ## Capture the latest changes
  6107. # Current object
  6108. try:
  6109. self.collection.get_active().read_form()
  6110. except:
  6111. self.log.debug("There was no active object")
  6112. pass
  6113. # Project options
  6114. self.options_read_form()
  6115. # Serialize the whole project
  6116. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6117. "options": self.options,
  6118. "version": self.version}
  6119. if self.defaults["global_save_compressed"] is True:
  6120. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6121. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6122. # # Write
  6123. f.write(g)
  6124. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6125. else:
  6126. # Open file
  6127. try:
  6128. f = open(filename, 'w')
  6129. except IOError:
  6130. App.log.error("Failed to open file for saving: %s", filename)
  6131. return
  6132. # Write
  6133. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6134. f.close()
  6135. # verification of the saved project
  6136. # Open and parse
  6137. try:
  6138. saved_f = open(filename, 'r')
  6139. except IOError:
  6140. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6141. return
  6142. try:
  6143. saved_d = json.load(saved_f, object_hook=dict2obj)
  6144. except:
  6145. self.inform.emit(
  6146. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6147. f.close()
  6148. return
  6149. saved_f.close()
  6150. if 'version' in saved_d:
  6151. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6152. else:
  6153. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6154. def on_options_app2project(self):
  6155. """
  6156. Callback for Options->Transfer Options->App=>Project. Copies options
  6157. from application defaults to project defaults.
  6158. :return: None
  6159. """
  6160. self.report_usage("on_options_app2project")
  6161. self.defaults_read_form()
  6162. self.options.update(self.defaults)
  6163. self.options_write_form()
  6164. def on_options_project2app(self):
  6165. """
  6166. Callback for Options->Transfer Options->Project=>App. Copies options
  6167. from project defaults to application defaults.
  6168. :return: None
  6169. """
  6170. self.report_usage("on_options_project2app")
  6171. self.options_read_form()
  6172. self.defaults.update(self.options)
  6173. self.defaults_write_form()
  6174. def on_options_project2object(self):
  6175. """
  6176. Callback for Options->Transfer Options->Project=>Object. Copies options
  6177. from project defaults to the currently selected object.
  6178. :return: None
  6179. """
  6180. self.report_usage("on_options_project2object")
  6181. self.options_read_form()
  6182. obj = self.collection.get_active()
  6183. if obj is None:
  6184. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6185. return
  6186. for option in self.options:
  6187. if option.find(obj.kind + "_") == 0:
  6188. oname = option[len(obj.kind) + 1:]
  6189. obj.options[oname] = self.options[option]
  6190. obj.to_form() # Update UI
  6191. def on_options_object2project(self):
  6192. """
  6193. Callback for Options->Transfer Options->Object=>Project. Copies options
  6194. from the currently selected object to project defaults.
  6195. :return: None
  6196. """
  6197. self.report_usage("on_options_object2project")
  6198. obj = self.collection.get_active()
  6199. if obj is None:
  6200. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6201. return
  6202. obj.read_form()
  6203. for option in obj.options:
  6204. if option in ['name']: # TODO: Handle this better...
  6205. continue
  6206. self.options[obj.kind + "_" + option] = obj.options[option]
  6207. self.options_write_form()
  6208. def on_options_object2app(self):
  6209. """
  6210. Callback for Options->Transfer Options->Object=>App. Copies options
  6211. from the currently selected object to application defaults.
  6212. :return: None
  6213. """
  6214. self.report_usage("on_options_object2app")
  6215. obj = self.collection.get_active()
  6216. if obj is None:
  6217. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6218. return
  6219. obj.read_form()
  6220. for option in obj.options:
  6221. if option in ['name']: # TODO: Handle this better...
  6222. continue
  6223. self.defaults[obj.kind + "_" + option] = obj.options[option]
  6224. self.defaults_write_form()
  6225. def on_options_app2object(self):
  6226. """
  6227. Callback for Options->Transfer Options->App=>Object. Copies options
  6228. from application defaults to the currently selected object.
  6229. :return: None
  6230. """
  6231. self.report_usage("on_options_app2object")
  6232. self.defaults_read_form()
  6233. obj = self.collection.get_active()
  6234. if obj is None:
  6235. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6236. return
  6237. for option in self.defaults:
  6238. if option.find(obj.kind + "_") == 0:
  6239. oname = option[len(obj.kind) + 1:]
  6240. obj.options[oname] = self.defaults[option]
  6241. obj.to_form() # Update UI
  6242. # end of file